Python:如何比较 unicode 和 ascii 文本?
我正在尝试将一个列表中的字符转换为日语中同一索引处的另一个列表中的字符(对于感兴趣的人,将 zenkaku 转换为 Hangaku moji),但我无法进行比较。我在比较之前解码为 utf-8(解码为 ascii 破坏了程序),但比较不会返回 true。有谁知道我做错了什么?这是代码(由于 SO 的编辑器,缩进有点古怪):
#!C:\Python27\python.exe
# coding=utf-8
import os
import shutil
import sys
zk = [
'。',
'、',
'「',
'」',
'(',
')',
'!',
'?',
'・',
'/',
'ア','イ','ウ','エ','オ',
'カ','キ','ク','ケ','コ',
'サ','シ','ス','セ','ソ',
'ザ','ジ','ズ','ゼ','ゾ',
'タ','チ','ツ','テ','ト',
'ダ','ヂ','ヅ','デ','ド',
'ラ','リ','ル','レ','ロ',
'マ','ミ','ム','メ','モ',
'ナ','ニ','ヌ','ネ','ノ',
'ハ','ヒ','フ','ヘ','ホ',
'バ','ビ','ブ','ベ','ボ',
'パ','ピ','プ','ペ','ポ',
'ヤ','ユ','ヨ','ヲ','ン','ッ'
]
hk = [
'。',
'、',
'「',
'」',
'(',
')',
'!',
'?',
'・',
'/',
'ア','イ','ウ','エ','オ',
'カ','キ','ク','ケ','コ',
'サ','シ','ス','セ','ソ',
'ザ','ジ','ズ','ゼ','ゾ',
'タ','チ','ツ','テ','ト',
'ダ','ヂ','ヅ','デ','ド',
'ラ','リ','ル','レ','ロ',
'マ','ミ','ム','メ','モ',
'ナ','ニ','ヌ','ネ','ノ',
'ハ','ヒ','フ','ヘ','ホ',
'バ','ビ','ブ','ベ','ボ',
'パ','ピ','プ','ペ','ポ',
'ヤ','ユ','ヨ','ヲ','ン','ッ'
]
def main():
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
print("Please specify a file to check.")
return
try:
f = open(filename, 'r')
except IOError as e:
print("Sorry! The file doesn't exist.")
return
filecontent = f.read()
f.close()
#y = zk[29]
#print y.decode('utf-8')
for f in filecontent:
for z in zk:
if f == z.decode('utf-8'):
print f
print filename
if __name__ == "__main__":
main()
我错过了一个步骤吗?
I'm trying to convert characters in one list into characters in another list at the same index in Japanese (zenkaku to hangaku moji, for those interested), and I can't get the comparison to work. I am decoding into utf-8 before I compare (decoding into ascii broke the program), but the comparison doesn't ever return true. Does anyone know what I'm doing wrong? Here's the code (indents are a little wacky due to SO's editor):
#!C:\Python27\python.exe
# coding=utf-8
import os
import shutil
import sys
zk = [
'。',
'、',
'「',
'」',
'(',
')',
'!',
'?',
'・',
'/',
'ア','イ','ウ','エ','オ',
'カ','キ','ク','ケ','コ',
'サ','シ','ス','セ','ソ',
'ザ','ジ','ズ','ゼ','ゾ',
'タ','チ','ツ','テ','ト',
'ダ','ヂ','ヅ','デ','ド',
'ラ','リ','ル','レ','ロ',
'マ','ミ','ム','メ','モ',
'ナ','ニ','ヌ','ネ','ノ',
'ハ','ヒ','フ','ヘ','ホ',
'バ','ビ','ブ','ベ','ボ',
'パ','ピ','プ','ペ','ポ',
'ヤ','ユ','ヨ','ヲ','ン','ッ'
]
hk = [
'。',
'、',
'「',
'」',
'(',
')',
'!',
'?',
'・',
'/',
'ア','イ','ウ','エ','オ',
'カ','キ','ク','ケ','コ',
'サ','シ','ス','セ','ソ',
'ザ','ジ','ズ','ゼ','ゾ',
'タ','チ','ツ','テ','ト',
'ダ','ヂ','ヅ','デ','ド',
'ラ','リ','ル','レ','ロ',
'マ','ミ','ム','メ','モ',
'ナ','ニ','ヌ','ネ','ノ',
'ハ','ヒ','フ','ヘ','ホ',
'バ','ビ','ブ','ベ','ボ',
'パ','ピ','プ','ペ','ポ',
'ヤ','ユ','ヨ','ヲ','ン','ッ'
]
def main():
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
print("Please specify a file to check.")
return
try:
f = open(filename, 'r')
except IOError as e:
print("Sorry! The file doesn't exist.")
return
filecontent = f.read()
f.close()
#y = zk[29]
#print y.decode('utf-8')
for f in filecontent:
for z in zk:
if f == z.decode('utf-8'):
print f
print filename
if __name__ == "__main__":
main()
Am I missing a step?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一些。
既然艰苦的工作已经完成,我会让你解决剩下的事情。
Several.
I'll let you work out the rest now that the hard work's been done.
确保
zk
和hk
列表包含 Unicode 字符串。使用 Unicode 文字,例如u'a'
或在运行时解码它们:您可以使用
unicode.translate()
将一个列表中的字符转换为另一个列表中的字符相同的索引:Make sure that
zk
andhk
lists contain Unicode strings. Either use Unicode literals e.g.,u'a'
or decode them at runtime:You could use
unicode.translate()
to convert characters in one list into characters in another list at the same index:你需要将所有内容转换为相同的形式,而形式就是 Unicode 字符串。 Unicode 字符串没有
.encode()
或.decode()
意义上的编码。当有一个非 unicode 字符串时,它实际上是一个字节流,以某种编码方式表达该值。转换为 Unicode 时,必须.decode()
。将 Unicode 字符串存储为字节序列时,必须将抽象.encode()
转换为具体字节。这样,当从 UTF-8 编码文件加载 Unicode 字符串时,或者您必须将其读入旧字符串(非 Unicode,字节序列),然后
.decode('utf-8')
,或者你可以使用`codecs.open(...,encoding='utf-8')——然后你会自动获得Unicode字符串。#coding=utf-8
的形式并不常见,但是如果编辑器(我的意思是你用来编写文本的工具)也这么认为的话,那就没问题了。然后编辑器会正确显示旧字符串。在这种情况下,应该对它们进行.decode('utf-8')
以获得 Unicode。同一源中仅包含 ASCII 字符的旧字符串也可以使用.decode('utf-8')
转换为 Unicode。总结一下:您正在从字节de编码为Unicode,并且您正在en将Unicode字符串编码为字节序列。从这个问题来看,你似乎在做相反的事情。
以下是完全错误的:
因为
filecontent
是f.read()
的结果。这样它就是一个字节序列。循环中的f
是一个字节。 z.decode('utf-8') 返回一个 Unicode 字符。他们无法相提并论。 (顺便说一下,f
是一种字节值的误导性名称。)You need to convert everything to the same form, and the form is Unicode strings. Unicode strings have no encoding in the sense
.encode()
or.decode()
. When having a non-unicode string, it is actually a stream of bytes that expresses the value in some encoding. When converting to Unicode, you have to.decode()
. When storing Unicode string to a sequence of bytes, you have to.encode()
the abstraction to concrete bytes.This way, when loading Unicode strings from an UTF-8 encoded file, or you have to read it into the old strings (non Unicode, sequences of bytes) and then
.decode('utf-8')
, or you can use `codecs.open(..., encoding='utf-8') -- then you get Unicode strings automatically.The form
# coding=utf-8
is not the usual, but it is OK... if the editor (I mean the tool that you use to write the text) also thinks this way. Then the old strings are displayed by the editor correctly. In the case they should be.decode('utf-8')
d to get Unicode. Old strings with ASCII characters only in the same source can also be converted to Unicode using the.decode('utf-8')
.To summarize: you are de coding from bytes to Unicode, and you are en coding the Unicode strings into sequence of bytes. It seems from the question that you are doing the opposite.
The following is completely wrong:
because the
filecontent
is the result off.read()
. This way it is a sequence of bytes. Thef
in the loop is one byte. The z.decode('utf-8') returns one Unicode character. They cannot be compared. (By the way, thef
is a kind of misleading name for a byte value.)