Python嵌套列表替换字符串中的unicode字符

标签 python unicode replace

尝试替换或删除此列表中的字符串以插入到不允许它们的数据库中

info=[[u'\xa0Buffalo\u2019s League of legends ...', '2012-09-05'], [u' \xa0RCKIN 0 - 1 WITHACK.nq\xa0  ', u'\xa0Buffalo\u2019s League of legends ...', '2012-09-05']]

我用过这段代码

info = [[x.replace(u'\xa0', u'') for x in l] for l in info]
info = [[y.replace('\u2019s', '') for y in o] for o in info]

第一行有效,但第二行无效,有什么建议吗?

最佳答案

放下第二行并执行:

info = [[x.encode('ascii', 'ignore')  for x in l] for l in info]

然后看看结果是否可以接受。这将尝试将所有 unicode 转换为 ascii 并删除所有转换失败的字符。您只是想确定如果您丢失了一个重要的 unicode 字符,这不是问题。

>>> info=[[u'\xa0Buffalo\u2019s League of legends ...', '2012-09-05'], [u' \xa0RCKIN 0 - 1 WITHACK.nq\xa0  ', u'\xa0Buffalo\u2019s League of legends ...', '2012-09-05']]
>>> info = [[x.encode('ascii', 'ignore')  for x in l] for l in info]
>>> info
[['Buffalos League of legends ...', '2012-09-05'], [' RCKIN 0 - 1 WITHACK.nq  ', 'Buffalos League of legends ...', '2012-09-05']]

发生了什么:

您的 Python 程序中的数据是 Unicode(这很好。)

>>> u = u'\u2019'

为了实现互操作性,最佳实践是将 Unicode 字符串写入 utf-8。这些是您应该存储在数据库中的字节:

>>> u.encode('utf-8')
'\xe2\x80\x99'
>>> utf8 = u.encode('utf-8')
>>> print utf8
’

然后当您将这些字节读回您的程序时,您应该对它们进行解码:

>>> utf8.decode('utf8')
u'\u2019'
>>> print utf8.decode('utf8')
’

如果您的数据库无法处理 utf-8,那么我会考虑获取一个新数据库。

关于Python嵌套列表替换字符串中的unicode字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22228209/

相关文章:

Python:定义多个相同类型的变量?

php - MySQL 数据库中的数据在网站中无法正确显示

c++ 无法获取 "wcout"来打印 unicode,并让 "cout"继续工作

visual-studio - 如何告诉 Visual Studio 2010 记住“查找”对话框的位置?

java - java中的ruby gsub函数,可能是replaceAll?

python - tensorflow :未创建XLA设备,未设置tf_xla_enable_xla_devices

python - 删除 pandas 中多索引数据框中的重复项

c - 用 C 宏替换部分函数/变量名

python - Hadoop 流 : reporting error

html - unicode字符是什么 代表?