如何将 Unicode 字符串(包含额外的字符,如 £ $ 等)转换为 Python 字符串?
print type(unicode_string), repr(unicode_string)
Python 3.x : print type(unicode_string), ascii(unicode_string)
然后编辑您的问题并复制/粘贴上述打印语句的结果。不要重新输入结果。还要查看 HTML 顶部附近的内容,看看是否可以找到类似的内容:<meta http-equiv="Content-Type" content="text/html; charset=iso-8859
unicode_string = u"I'm unicode string"; bytestring = unicode_string.encode('utf-8'); unicode_again = bytestring.decode('utf-8')
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'
如果您不需要翻译非 ASCII 字符,则可以使用 encode to ASCII:
>>> a=u"aaaàçççñññ"
>>> type(a)
<type 'unicode'>
>>> a.encode('ascii','ignore')
'aaa'
>>> a.encode('ascii','replace')
'aaa???????'
>>>
ignore
与 replace
效果的精彩演示
a.encode('ascii', 'xmlcharrefreplace')
给出 'aaaàçççñññ'
。
type(a)
在 Python 3.6.8 中是 str
,并且没有任何 encode()
方法。
>>> text=u'abcd'
>>> str(text)
'abcd'
如果字符串只包含 ascii 字符。
如果您有一个 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 中的默认字符串对象)进行转换.
这是一个例子:
>>> u = u'€€€'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'
utf8
时,结果只是问号?这是我的 Python 版本 2.7.13 的 an image。 (我可以编码其他 unicode 对象,如 u"Klüft"
,但不能编码欧元?)
文件包含 unicode-esaped 字符串
\"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'
result.encode().decode('unicode-escape')
好吧,如果您愿意/准备好切换到 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,那么问题可能与您尝试将文本保存到文件的方式有关。)
有一个名为 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/
点安装 ftfy
https://pypi.org/project/ftfy/
这是一个示例代码
import unicodedata
raw_text = u"here $%6757 dfgdfg"
convert_text = unicodedata.normalize('NFKD', raw_text).encode('ascii','ignore')
没有答案适用于我的情况,我有一个包含 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
这是我的功能
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')
我制作了以下功能,可让您根据 Unicode (https://www.unicode.org/reports/tr44/#General_Category_Values) 中的 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
字符串转换为str
的 only 方法是删除或转换无法用 ASCII 表示的字符。所以我+1。type(title) == unicode and type(title.encode('utf-8')) == str
。无需破坏输入,即可获得可以保存到文件的字节串。