尝试替换或删除此列表中的字符串以插入到不允许它们的数据库中
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/