Python3 写入中文(utf-8)到文本,还是会出现乱码?

2017-09-04 16:53:42 +08:00
 rogwan

MySQL 数据库里存的数据是 utf-8,python3 写入文本,还是会出乱码:

news = News.query.filter_by(news_id=news_id).first()
f = open('news.txt', 'w')
f.write(news.content)
f.close()

news.content 文章内容是全英文的 OK,文章里面有中文就是乱码。

8779 次点击
所在节点    Python
16 条回复
yunkchen
2017-09-04 16:57:09 +08:00
rogwan
2017-09-04 17:07:20 +08:00
@yunkchen 试过加 encoding='utf-8':

f = open('news.txt', 'w', encoding='utf-8')

中文还是乱码。
fanhaipeng0403
2017-09-04 17:09:39 +08:00
数据库编码设置,驱动编码设置
ltux
2017-09-04 17:13:07 +08:00
先搞清楚 news.content 是 bytes 还是 str
rogwan
2017-09-04 17:27:57 +08:00
@ltux print(type(news.content)) 是 str 啊

news.content <class 'str'>
geofvt
2017-09-04 17:30:01 +08:00
news.content 需要编码转换
或者用 beautifulsoup 的 prettify()
https://gist.github.com/ercJuL/97e27d199451d43f93f14d41625955c9
petelin
2017-09-04 17:39:13 +08:00
乱码贴出来看看
rogwan
2017-09-04 17:47:29 +08:00
@petelin

<p>中文字符</p>

中文字符
ltux
2017-09-04 18:06:15 +08:00
我猜 new.content 里面是原内容以 utf-8 编码之后又原封不动转换成了对应的 str。所以解决方法是先原封不动转换成 bytes, 再按 utf-8 解码,即:news.content.encode('latin-1').decode('utf-8')

说到底还是数据库驱动设置的问题。
ltux
2017-09-04 18:09:44 +08:00
如上,写入的时候把 f.write( news.content ) 换成 f.write( news.content.encode('latin-1').decode('utf-8') ) 八成就行了。
xhp281
2017-09-04 18:34:38 +08:00
f = open('news.txt', 'w', encoding='utf-8') 这样子不行?你打印的时候是不是乱码
rogwan
2017-09-04 19:33:35 +08:00
@ltux
@xhp281

呃,貌似不是数据库里编码的问题,有点奇怪,IDE 环境里 f.write('中文字符') 写中文都是乱码。直接 IDLE 写 f.write('中文字符') 没问题。把 IDE 里的 *.py 文件全部重新 encode 一下,现在好了
mcfog
2017-09-04 19:53:23 +08:00
赌五毛楼主是 windows 环境,赌一块楼主不知道什么是 BOM
rogwan
2017-09-04 20:05:21 +08:00
@mcfog 你先把 5 毛掏出来先,哈哈😄 全部是 ubuntu 环境 server 和 desktop (只是用了一次 idle ) bom 在这个 debug 里为什么要出现?
flynaj
2017-09-04 20:28:56 +08:00
.py 文件也要保存成 UTF-8,新手问题
likuku
2017-09-04 22:12:46 +08:00
先确认你数据库内数据表的编码是 utf8,数据库连接是 utf8,数据存取时是 utf8,原始数据是 utf8 编码

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/388090

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX