将 Unicode 字符串转换为 Python 中的字符串(包含额外符号)

问题描述 投票:0回答:12

如何将 Unicode 字符串(包含 £ $ 等额外字符)转换为 Python 字符串?

string unicode type-conversion python-2.x
12个回答
625
投票

参见

unicodedata.normalize

title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
'Kluft skrams infor pa federal electoral groe'

341
投票

如果不需要翻译非 ASCII 字符,可以使用编码为 ASCII:

>>> a=u"aaaàçççñññ"
>>> type(a)
<type 'unicode'>
>>> a.encode('ascii','ignore')
'aaa'
>>> a.encode('ascii','replace')
'aaa???????'
>>>

158
投票
>>> text=u'abcd'
>>> str(text)
'abcd'

如果字符串只包含ascii字符。


122
投票

如果您有一个 Unicode 字符串,并且想要将其写入文件或其他序列化形式,则必须首先将其编码为可以存储的特定表示形式。有几种常见的 Unicode 编码,例如 UTF-16(大多数 Unicode 字符使用两个字节)或 UTF-8(1-4 字节/代码点,具体取决于字符)等。要将该字符串转换为特定编码,您可以可以使用:

>>> s= u'£10'
>>> s.encode('utf8')
'\xc2\x9c10'
>>> s.encode('utf16')
'\xff\xfe\x9c\x001\x000\x00'

这个原始字节字符串可以写入文件。但是,请注意,在读回它时,您必须知道它的编码方式并使用相同的编码对其进行解码。

写入文件时,您可以使用 codecs 模块摆脱这种手动编码/解码过程。因此,要打开将所有 Unicode 字符串编码为 UTF-8 的文件,请使用:

import codecs
f = codecs.open('path/to/file.txt','w','utf8')
f.write(my_unicode_string)  # Stored on disk as UTF-8

请注意,使用这些文件的其他任何人如果想要读取这些文件,就必须了解文件的编码方式。如果您是唯一进行读/写的人,这不是问题,否则请确保您以其他使用该文件的任何人都可以理解的形式进行编写。

在 Python 3 中,这种文件访问形式是默认的,内置

open
函数将采用编码参数,并且对于以文本方式打开的文件,始终在 Unicode 字符串(Python 3 中的默认字符串对象)之间进行转换模式。


60
投票

这是一个例子:

>>> u = u'€€€'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'

12
投票

在我的例子中,文件包含 unicode-esaped 字符串:

line = "\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0437\\u0430\\u0446\\u0438\\u044f .....\","

我的解决方案是:

f  = open("file-json.log", encoding="utf-8")
qq = f.readline() 

print(qq)                          
# {"log":\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0440\\u0438\\u0437\\u0430\\u0446\\u0438\\u044f \\u043f\\u043e\\u043b\\u044c\\u0437\\u043e\\u0432\\u0430\\u0442\\u0435\\u043b\\u044f\"}

print(qq.encode().decode("unicode-escape").encode().decode("unicode-escape")) 
# '{"log":"message": "Авторизация пользователя"}\n'

6
投票

好吧,如果您愿意/准备好切换到 Python 3(您可能不会因为与某些 Python 2 代码向后不兼容),则无需进行任何转换; Python 3 中的所有文本都用 Unicode 字符串表示,这也意味着不再使用

u'<text>'
语法。实际上,您还拥有字节字符串,用于表示数据(可能是编码字符串)。

http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

(当然,如果您当前使用的是 Python 3,那么问题可能与您尝试将文本保存到文件的方式有关。)


5
投票

有一个名为 ftfy 的库可以帮助解决 Unicode 问题。让我的生活更轻松。

示例1

import ftfy
print(ftfy.fix_text('ünicode'))

output -->
ünicode

示例 2 - UTF-8

import ftfy
print(ftfy.fix_text('\xe2\x80\xa2'))

output -->
•

示例 3 - Unicode 代码点

import ftfy
print(ftfy.fix_text(u'\u2026'))

output -->
…

https://ftfy.readthedocs.io/en/latest/

pip 安装 ftfy

https://pypi.org/project/ftfy/


3
投票

这是示例代码

import unicodedata    
raw_text = u"here $%6757 dfgdfg"
convert_text = unicodedata.normalize('NFKD', raw_text).encode('ascii','ignore')

2
投票

没有答案适合我的情况,我有一个包含 unicode 字符的字符串变量,并且这里解释的编码解码没有完成这项工作。

如果我在终端中执行

echo "no me llama mucho la atenci\u00f3n"

python3
>>> print("no me llama mucho la atenci\u00f3n")

输出正确:

output: no me llama mucho la atención

但是使用加载此字符串变量的脚本不起作用。

这就是我的案例,以防对任何人有帮助:

string_to_convert = "no me llama mucho la atenci\u00f3n"
print(json.dumps(json.loads(r'"%s"' % string_to_convert), ensure_ascii=False))
output: no me llama mucho la atención

1
投票

这是我的职责

import unicodedata
def unicode_to_ascii(note):
    str_map = {'Š' : 'S', 'š' : 's', 'Đ' : 'D', 'đ' : 'd', 'Ž' : 'Z', 'ž' : 'z', 'Č' : 'C', 'č' : 'c', 'Ć' : 'C', 'ć' : 'c', 'À' : 'A', 'Á' : 'A', 'Â' : 'A', 'Ã' : 'A', 'Ä' : 'A', 'Å' : 'A', 'Æ' : 'A', 'Ç' : 'C', 'È' : 'E', 'É' : 'E', 'Ê' : 'E', 'Ë' : 'E', 'Ì' : 'I', 'Í' : 'I', 'Î' : 'I', 'Ï' : 'I', 'Ñ' : 'N', 'Ò' : 'O', 'Ó' : 'O', 'Ô' : 'O', 'Õ' : 'O', 'Ö' : 'O', 'Ø' : 'O', 'Ù' : 'U', 'Ú' : 'U', 'Û' : 'U', 'Ü' : 'U', 'Ý' : 'Y', 'Þ' : 'B', 'ß' : 'Ss', 'à' : 'a', 'á' : 'a', 'â' : 'a', 'ã' : 'a', 'ä' : 'a', 'å' : 'a', 'æ' : 'a', 'ç' : 'c', 'è' : 'e', 'é' : 'e', 'ê' : 'e', 'ë' : 'e', 'ì' : 'i', 'í' : 'i', 'î' : 'i', 'ï' : 'i', 'ð' : 'o', 'ñ' : 'n', 'ò' : 'o', 'ó' : 'o', 'ô' : 'o', 'õ' : 'o', 'ö' : 'o', 'ø' : 'o', 'ù' : 'u', 'ú' : 'u', 'û' : 'u', 'ý' : 'y', 'ý' : 'y', 'þ' : 'b', 'ÿ' : 'y', 'Ŕ' : 'R', 'ŕ' : 'r'}
    for key, value in str_map.items():
        note = note.replace(key, value)
    asciidata = unicodedata.normalize('NFKD', note).encode('ascii', 'ignore')
    return asciidata.decode('UTF-8')

1
投票

我制作了以下函数,可让您根据 Unicode 中的 General_Category_Values 控制要保留的内容 (https://www.unicode.org/reports/tr44/#General_Category_Values)

def FormatToNameList(name_str):
    import unicodedata
    clean_str = ''
    for c in name_str:
        if unicodedata.category(c) in ['Lu','Ll']:
            clean_str += c.lower()
            print('normal letter: ',c)
        elif unicodedata.category(c) in ['Lt','Lm','Lo']:
            clean_str += c
            print('special letter: ',c)
        elif unicodedata.category(c) in ['Nd']:
            clean_str += c
            print('normal number: ',c)
        elif unicodedata.category(c) in ['Nl','No']:
            clean_str += c
            print('special number: ',c)
        elif unicodedata.category(c) in ['Cc','Sm','Zs','Zl','Zp','Pc','Pd','Ps','Pe','Pi','Pf','Po']:
            clean_str += ' '
            print('space or symbol: ',c)
        else:
            print('other: ',' : ',c,' unicodedata.category: ',unicodedata.category(c))    
    name_list = clean_str.split(' ')
    return clean_str, name_list
if __name__ == '__main__':
     u = 'some3^?"Weirdstr '+ chr(231) + chr(0x0af4)
     [clean_str, name_list] = FormatToNameList(u)
     print(clean_str)
     print(name_list)

另请参阅 https://docs.python.org/3/howto/unicode.html

© www.soinside.com 2019 - 2024. All rights reserved.