如何将Unicode字符串(包含额外的字符,如£$等)转换为Python字符串?
当前回答
我已经做了下面的函数,它可以让你控制什么要保留根据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字符串
\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0437\\u0430\\u0446\\u0438\\u044f .....\",
对我来说
f = open("56ad62-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\"}
(qq.encode().decode("unicode-escape").encode().decode("unicode-escape"))
# '{"log":"message": "Авторизация пользователя"}\n'
在我的例子中,没有答案,因为我有一个包含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
如果您有一个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中的默认字符串对象)。
>>> text=u'abcd'
>>> str(text)
'abcd'
如果字符串只包含ascii字符。
有一个库可以帮助解决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/
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- Printf与std::字符串?
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if