我在理解文本读取和写入文件时遇到了一些大脑失败(Python 2.4).
# The string, which has an a-acute in it.
ss = u'Capit\xe1n'
ss8 = ss.encode('utf8')
repr(ss), repr(ss8)
Run Code Online (Sandbox Code Playgroud)
("u'Capit\xe1n'","'Capit\xc3\xa1n'")
print ss, ss8
print >> open('f1','w'), ss8
>>> file('f1').read()
'Capit\xc3\xa1n\n'
Run Code Online (Sandbox Code Playgroud)
所以我输入Capit\xc3\xa1n我最喜欢的编辑器,在文件f2中.
然后:
>>> open('f1').read()
'Capit\xc3\xa1n\n'
>>> open('f2').read()
'Capit\\xc3\\xa1n\n'
>>> open('f1').read().decode('utf8')
u'Capit\xe1n\n'
>>> open('f2').read().decode('utf8')
u'Capit\\xc3\\xa1n\n'
Run Code Online (Sandbox Code Playgroud)
我在这里不理解什么?显然,我缺少一些重要的魔法(或者很有道理).在文本文件中键入什么来获得正确的转换?
我真正没有想到的是,UTF-8表示的重点是,如果你真的不能让Python识别它,那么它来自外部.也许我应该只是JSON转储字符串,并使用它,因为它有一个asciiable表示!更重要的是,当从文件进入时,Python会识别和解码这个Unicode对象的ASCII表示吗?如果是这样,我怎么得到它?
>>> print simplejson.dumps(ss)
'"Capit\u00e1n"'
>>> print >> file('f3','w'), simplejson.dumps(ss)
>>> simplejson.load(open('f3'))
u'Capit\xe1n'
Run Code Online (Sandbox Code Playgroud) 我收到了一些编码的文本,但我不知道使用了什么字符集.有没有办法使用Python确定文本文件的编码?如何检测文本文件的编码/代码页处理C#.
我正在使用Python-2.6 CGI脚本,但在服务器日志中发现此错误json.dumps(),
Traceback (most recent call last):
File "/etc/mongodb/server/cgi-bin/getstats.py", line 135, in <module>
print json.dumps(??__get?data())
File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte
Run Code Online (Sandbox Code Playgroud)
在这里,
?__get?data()功能返回dictionary {}.
在发布这个问题之前,我已经提到了这个问题.
以下行是伤害JSON编码器,
now = datetime.datetime.now()
now = datetime.datetime.strftime(now, '%Y-%m-%dT%H:%M:%S.%fZ')
print json.dumps({'current_time': now}) …Run Code Online (Sandbox Code Playgroud) 我在这段代码中看到一个字符串:
data[:2] == '\xff\xfe'
Run Code Online (Sandbox Code Playgroud)
我不知道'\ xff\xfe'是什么,
所以我想逃避它,但没有成功
import cgi
print cgi.escape('\xff\xfe')#print \xff\xfe
Run Code Online (Sandbox Code Playgroud)
我怎么才能得到它.
谢谢