消除lis中的unicode字符

2024-03-29 07:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试过str()和x.encode('UTF8')。 有没有一种快速简单的方法来删除unicode字符? 我的列表如下:

mcd = [u'Chicken saut\xc3\xa9ed potatoes',  'Roasted lamb with mash potatoes', 'Rabbit casserole with tarragon, mushrooms and dijon mustard sauce. Served with mash potatoes']

我想去掉u的原因是因为我想把这些数据复制到CSV文件中。当我试图这样做时,它会给我一个像下面这样的错误。。。在

UnicodeEncodeError:“ascii”编解码器无法对位置8-10的字符进行编码:序号不在范围内(128)

我认为完全删除unicode会更容易些。在

提前谢谢!在


Tags: 方法列表withunicodeutf8字符encodemash
3条回答

问题可能是按enter键而不是打印结果。这将调用repr而不是str。引用文件:

In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. reference

让我给你看看:

In [1]: mcd = [u'Chicken saut\xc3\xa9ed potatoes',  'Roasted lamb with mash potatoes', 'Rabbit casserole with tarragon, mushrooms and dijon mustard sauce. Served with mash potatoes']

In [2]: mcd[0]
Out[2]: u'Chicken saut\xc3\xa9ed potatoes'

In [3]: print repr(mcd[0])
u'Chicken saut\xc3\xa9ed potatoes'

In [4]: print mcd[0]  # Here will use my current OS encoding, i think utf8 in my case
Chicken sautéed potatoes

In [5]: print mcd[0].encode('utf8')  # yes! i was right
Chicken sautéed potatoes

你应该先选择编码类型,我想在这种情况下你必须使用拉丁语1:

^{pr2}$

希望能帮上忙。在

编辑: 我没有看到问题的编辑,如果你想替换字符,check this answer

这对我有用:

mcd = [u'Chicken saut\xc3\xa9ed potatoes',  'Roasted lamb with mash potatoes', 'Rabbit casserole with tarragon, mushrooms and dijon mustard sauce. Served with mash potatoes']

new = [str(m) for m in mcd]

for m,n in zip(mcd,new): # compare before and after
    print type(m), type(n)

输出:

^{pr2}$

如果上述方法不起作用(见注释中的护航):

new = [m.encode('utf-8') for m in mcd]

如果您获得的字符串是网站抓取的结果,则表明您获取的字符串的编码设置不正确。在

站点通常会指定charset=utf-8,然后将站点的内容放在其他字符集中(尤其是windows-1252),反之亦然。对于这种现象(也称为mojibake),没有简单、通用的解决方法。在

您可能需要尝试使用不同的抓取库大多数都有一些识别和处理这种情况的策略,但是它们在不同的场景中有不同的成功率。如果您使用的是beauthoulsoup,那么您可能需要对chardet后端使用不同的参数。在

当然,如果您只关心正确地抓取一个站点,您可以硬编码该站点声明的字符编码的覆盖。在

你这样的问题没什么意义。你到底想达到什么目的还不清楚。u'Chicken and sauted potatoes'并不比u'Chicken and sautéed potatoes'更正确,也只是稍微不那么吸引人(而且在某些方面更不吸引人,因为你无法判断是否有人试图使它正确,尽管它没有被恰当地执行)。在

如果由于将Unicode输入到使用ASCII编码的文件句柄而出现编码错误,正确的解决方案是在打开文件进行写入时指定ASCII以外的编码(通常是UTF-8)。在

相关问题 更多 >