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


当前回答

>>> text=u'abcd'
>>> str(text)
'abcd'

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

其他回答

我已经做了下面的函数,它可以让你控制什么要保留根据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

在我的例子中,没有答案,因为我有一个包含unicode字符的字符串变量,这里解释的编码-解码都不起作用。

如果我在终点站做

echo "no me llama mucho la atenci\u00f3n"

or

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

下面是一个示例代码

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

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

示例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/

>>> text=u'abcd'
>>> str(text)
'abcd'

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