python unicode 错误:尽管我使用了编码(utf-8),但为什么我一直得到这个字符? [英] python unicode error : why do I keep getting this caracters although I used encode(utf-8)?

查看:46
本文介绍了python unicode 错误:尽管我使用了编码(utf-8),但为什么我一直得到这个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于文章2中的p:url = p.find('a')['href']title = p.find('h3').get_text().strip().encode("utf-8")打印(标题)

输出:

c3\xa9gie de d\xc3\xa9fense active et pr\xc3\xa9ventive\xc2\xbb'b'Zoom sur la course effr\xc3\xa9n\xc3\xa9e pour trouver un vaccin'b'on vous le dit'b'\xc3\x89dition du jour (PDF)'b'Son port est d\xc3\xa9sormais mustoire : Le prix du masque plafonn\xc3\xa9'b'Baisse de 20% des prix des produits agricoles' .....

解决方案

使用 split()join 来翻译字符.

i.e Zoom sur la course effr\xc3\xa9n\xc3\xa9e pour trouver un vaccin"joinsplit() 之后将是 'Zoom sur la course effrénée pour trouver un vaccin'>

然后 encodeascii 忽略错误 'ignore'decodeutf-8 这是为了去除é

等特殊字符

应该是这样的:

"".join(the_text_to_clean.strip()).encode('ascii', 'ignore').decode("utf-8")

它如何应用于您的代码

对于文章2中的p:url = p.find('a')['href']title = p.find('h3').get_text()title = "".join(title.strip()).encode('ascii', 'ignore').decode("utf-8") #clean title打印(标题)

for p in articles2:
    url = p.find('a')['href']
    title = p.find('h3').get_text().strip().encode("utf-8")
    print(title)

OUTPUT:

c3\xa9gie de d\xc3\xa9fense active et pr\xc3\xa9ventive\xc2\xbb'

b'Zoom sur la course effr\xc3\xa9n\xc3\xa9e pour trouver un vaccin'

b'On vous le dit'

b'\xc3\x89dition du jour (PDF)'

b'Son port est d\xc3\xa9sormais obligatoire : Le prix du masque plafonn\xc3\xa9'

b'Baisse de 20% des prix des produits agricoles' .....

解决方案

Use split() and join to translate the characters.

i.e "Zoom sur la course effr\xc3\xa9n\xc3\xa9e pour trouver un vaccin" will be 'Zoom sur la course effrénée pour trouver un vaccin' after join and split()

Then encode it to ascii ignoring errors 'ignore' and decode it to utf-8 this is in order to remove the special characters such as é

Should look like:

"".join(the_text_to_clean.strip()).encode('ascii', 'ignore').decode("utf-8")

How it applies in your code

for p in articles2:
   url = p.find('a')['href']
   title = p.find('h3').get_text()
   title = "".join(title.strip()).encode('ascii', 'ignore').decode("utf-8") #clean title
   print(title)

这篇关于python unicode 错误:尽管我使用了编码(utf-8),但为什么我一直得到这个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆