Gra*_*ton 94 python unicode encoding ascii
在文本文件中,有一个字符串"我不喜欢这个".
但是,当我把它读成字符串时,它变成了"我不喜欢这样".我明白\ u2018是"'"的unicode表示.我用
f1 = open (file1, "r")
text = f1.read()
Run Code Online (Sandbox Code Playgroud)
命令做阅读.
现在,是否有可能以这样的方式读取字符串:当它被读入字符串时,它是"我不喜欢这个",而不是像这样的"我不喜欢这样"?
第二次编辑:我看到有些人使用映射来解决这个问题,但实际上,是否没有内置转换可以将这种ANSI转换为unicode(反之亦然)转换?
Jay*_*Jay 147
参考:http://docs.python.org/howto/unicode
因此,从文件中读取Unicode非常简单:
import codecs
f = codecs.open('unicode.rst', encoding='utf-8')
for line in f:
print repr(line)
Run Code Online (Sandbox Code Playgroud)
也可以在更新模式下打开文件,允许读写:
f = codecs.open('test', encoding='utf-8', mode='w+')
f.write(u'\u4500 blah blah blah\n')
f.seek(0)
print repr(f.readline()[:1])
f.close()
Run Code Online (Sandbox Code Playgroud)
编辑:我假设您的预期目标只是能够将文件正确地读入Python中的字符串.如果您尝试从Unicode转换为ASCII字符串,那么实际上没有直接的方法,因为Unicode字符不一定存在于ASCII中.
如果您尝试转换为ASCII字符串,请尝试以下操作之一:
如果您只想处理一些特殊情况,例如此特定示例,请使用ASCII等效替换特定的unicode字符
使用unicodedata模块normalize()和string.encode()方法尽可能地转换为下一个最接近的ASCII等效值(参考https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting- unicode-to-ascii-using-python):
>>> teststr
u'I don\xe2\x80\x98t like this'
>>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
'I donat like this'
Run Code Online (Sandbox Code Playgroud)Dzi*_*inX 15
有几点需要考虑.
\ u2018字符可能仅作为Python中unicode字符串表示的片段出现,例如,如果您写:
>>> text = u'‘'
>>> print repr(text)
u'\u2018'
Run Code Online (Sandbox Code Playgroud)
现在,如果您只是想要巧妙地打印unicode字符串,只需使用unicode的encode方法:
>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I don‘t like this
Run Code Online (Sandbox Code Playgroud)
为了确保任何文件中的每一行都被读取为unicode,您最好使用该codecs.open函数而不仅仅是open,这允许您指定文件的编码:
>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I don‘t like this
Run Code Online (Sandbox Code Playgroud)
Ste*_*ein 11
也可以使用 python 3 读取方法读取编码的文本文件:
f = open (file.txt, 'r', encoding='utf-8')
text = f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)
有了这个变化,就不需要导入任何额外的库
但它确实是"我不喜欢这样"而不是"我不喜欢这个".字符u'\ u2018'是一个完全不同于"'"的字符(并且,在视觉上,应该更多地对应于''').
如果您尝试将编码的unicode转换为纯ASCII,则可以保留要转换为ASCII的unicode标点符号的映射.
punctuation = {
u'\u2018': "'",
u'\u2019': "'",
}
for src, dest in punctuation.iteritems():
text = text.replace(src, dest)
Run Code Online (Sandbox Code Playgroud)
然而,在unicode中有很多标点字符,但我想你可以指望它们中的一些实际上被创建你正在阅读的文档的任何应用程序所使用.