我在python中做一些脚本.我创建了一个保存在文件中的字符串.这个字符串有很多数据,来自目录的树状和文件名.根据convmv,我所有的树状花序都是UTF-8.
我想把所有内容都保存在UTF-8中,因为我之后会把它保存在MySQL中.现在,在UTF-8的MySQL中,我遇到了一些问题(比如é或è - 我是法国人).
我希望python总是使用字符串作为UTF-8.我在互联网上阅读了一些信息,我确实喜欢这个.
我的脚本以此开头:
#!/usr/bin/python
# -*- coding: utf-8 -*-
def createIndex():
import codecs
toUtf8=codecs.getencoder('UTF8')
#lot of operations & building indexSTR the string who matter
findex=open('config/index/music_vibration_'+date+'.index','a')
findex.write(codecs.BOM_UTF8)
findex.write(toUtf8(indexSTR)) #this bugs!
Run Code Online (Sandbox Code Playgroud)
当我执行时,这里是答案: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2171: ordinal not in range(128)
编辑:我看到,在我的文件中,重音很好写.创建此文件后,我将其读取并将其写入MySQL.但我不明白为什么,但我遇到编码问题.我的MySQL数据库是在utf8中,或者似乎是SQL查询SHOW variables LIKE 'char%'只返回utf8或二进制.
我的功能看起来像这样:
#!/usr/bin/python
# -*- coding: utf-8 -*-
def saveIndex(index,date):
import MySQLdb as mdb
import codecs
sql = mdb.connect('localhost','admin','*******','music_vibration')
sql.charset="utf8"
findex=open('config/index/'+index,'r')
lines=findex.readlines()
for line in lines:
if line.find('#artiste') …Run Code Online (Sandbox Code Playgroud) 我下载了我的Facebook信使数据(在你的Facebook帐户中,转到设置,然后转到你的Facebook信息,然后下载你的信息,然后创建一个文件,至少选中了消息框)来做一些很酷的统计数据
但是编码有一个小问题.我不确定,但看起来Facebook对这些数据使用了错误的编码.当我用文本编辑器打开它时,我看到这样的事情:Rados\u00c5\u0082aw.当我尝试用python(UTF-8)打开它时,我得到了RadosÅ\x82aw.但是我应该得到:Rados?aw.
我的python脚本:
text = open(os.path.join(subdir, file), encoding='utf-8')
conversations.append(json.load(text))
Run Code Online (Sandbox Code Playgroud)
我尝试了一些最常见的编码.示例数据是:
{
"sender_name": "Rados\u00c5\u0082aw",
"timestamp": 1524558089,
"content": "No to trzeba ostatnie treningi zrobi\u00c4\u0087 xD",
"type": "Generic"
}
Run Code Online (Sandbox Code Playgroud)