Python:如何比较 unicode 和 ascii 文本?

发布于 2024-12-08 07:39:59 字数 1434 浏览 0 评论 0原文

我正在尝试将一个列表中的字符转换为日语中同一索引处的另一个列表中的字符(对于感兴趣的人,将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最后的乘客 2024-12-15 07:39:59

一些。

zk = [
u'。',
u'、',
u'「',
 ...

 ...
    f = codecs.open(filename, 'r', encoding='utf-8')
 ...

既然艰苦的工作已经完成,我会让你解决剩下的事情。

Several.

zk = [
u'。',
u'、',
u'「',
 ...

 ...
    f = codecs.open(filename, 'r', encoding='utf-8')
 ...

I'll let you work out the rest now that the hard work's been done.

等往事风中吹 2024-12-15 07:39:59

确保 zkhk 列表包含 Unicode 字符串。使用 Unicode 文字,例如 u'a' 或在运行时解码它们:

fromutf8 = lambda s: s.decode('utf-8') if not isinstance(s, unicode) else s
zk = map(fromutf8, zk)
hk = map(fromutf8, hk)

您可以使用 unicode.translate() 将一个列表中的字符转换为另一个列表中的字符相同的索引:

import codecs

translation_table = dict(zip(map(ord,zk), hk))
with codecs.open(sys.argv[1], encoding='utf-8') as f:
     for line in f:
         print line.translate(translation_table),

Make sure that zk and hk lists contain Unicode strings. Either use Unicode literals e.g., u'a' or decode them at runtime:

fromutf8 = lambda s: s.decode('utf-8') if not isinstance(s, unicode) else s
zk = map(fromutf8, zk)
hk = map(fromutf8, hk)

You could use unicode.translate() to convert characters in one list into characters in another list at the same index:

import codecs

translation_table = dict(zip(map(ord,zk), hk))
with codecs.open(sys.argv[1], encoding='utf-8') as f:
     for line in f:
         print line.translate(translation_table),
痴意少年 2024-12-15 07:39:59

你需要将所有内容转换为相同的形式,而形式就是 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字符串编码为字节序列。从这个问题来看,你似乎在做相反的事情。

以下是完全错误的:

for f in filecontent:
    for z in zk:
        if f == z.decode('utf-8'):
            print f

因为 filecontentf.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:

for f in filecontent:
    for z in zk:
        if f == z.decode('utf-8'):
            print f

because the filecontent is the result of f.read(). This way it is a sequence of bytes. The f in the loop is one byte. The z.decode('utf-8') returns one Unicode character. They cannot be compared. (By the way, the f is a kind of misleading name for a byte value.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文