简体   繁体   English

Python中的Unicode全宽到标准ASCII(和后面)

[英]Unicode full width to standard ASCII (and back) in Python

I need a method to convert a string from standard ASCII and Unicode FULLWIDTH characters and vice versa in pure Python 2.6. 我需要一种方法来从纯Python 2.6中转换标准ASCII和Unicode FULLWIDTH字符的字符串,反之亦然。 The string may also contain symbols. 该字符串也可能包含符号。

I tried unicodedata.normalize but it doesn't convert symbols, and that is one-way. 我尝试过unicodedata.normalize但它没有转换符号,这是单向的。 Other solutions found in other questions don't work well for my program (many don't convert symbols). 在其他问题中找到的其他解决方案对我的程序不起作用(许多不转换符号)。

I am trying to create a savefile reader/writer for the PS2. 我正在尝试为PS2创建一个savefile读/写器。 For example I read this string from the file: 例如,我从文件中读取此字符串:

'\x82g\x82\x81\x82\x8c\x82\x86\x81|\x82k\x82\x89\x82\x86\x82\x85\x82r\x82\x99\x82\x93\x82\x94\x82\x85\x82\x8d\x81@\x82c\x82\x81\x82\x94\x82\x81'

that is s-jis -encoded, I decode it with .decode('s-jis') : 这是s-jis -encoded,我用.decode('s-jis')解码它:

u'\uff28\uff41\uff4c\uff46\u2212\uff2c\uff49\uff46\uff45\uff33\uff59\uff53\uff54\uff45\uff4d\u3000\uff24\uff41\uff54\uff41'

and I print it: 我打印出来:

Half−LifeSystem Data

this is the FULLWIDTH string that I need to convert to ASCII; 这是我需要转换为ASCII的FULLWIDTH字符串; it should become this: 它应该变成这样:

'Half-LifeSystem Data'

(there is nothing between Life and System ) LifeSystem之间没有任何东西)

Note that I chose this save because it contains the two most recurring symbols, - and the space. 请注意,我选择了此保存,因为它包含两个最常见的符号-和空格。

Also, I must be able to re-encode it the same way it was, because the user may rename the save, so I have to take the string from the input dialog and write it to the file again. 此外,我必须能够以相同的方式对其进行重新编码,因为用户可以重命名保存,因此我必须从输入对话框中取出字符串并再次将其写入文件。

I'd use a unicode.translate() to map between the two sets; 我将使用unicode.translate()在两组之间进行映射; the characters map one-to-one: 角色一对一地图:

ascii_to_wide = dict((i, unichr(i + 0xfee0)) for i in range(0x21, 0x7f))
ascii_to_wide.update({0x20: u'\u3000', 0x2D: u'\u2212'})  # space and minus
wide_to_ascii = dict((i, unichr(i - 0xfee0)) for i in range(0xff01, 0xff5f))
wide_to_ascii.update({0x3000: u' ', 0x2212: u'-'})        # space and minus

wide_text.translate(wide_to_ascii)
ascii_text.translate(ascii_to_wide)

>>> wide_text.translate(wide_to_ascii)
u'Half-LifeSystem Data'
>>> wide_text.translate(wide_to_ascii).translate(ascii_to_wide)
u'\uff28\uff41\uff4c\uff46\u2212\uff2c\uff49\uff46\uff45\uff33\uff59\uff53\uff54\uff45\uff4d\u3000\uff24\uff41\uff54\uff41'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM