我已经广泛搜索,虽然有大量的资源可用于回答这个问题,但我似乎无法得到任何可行的答案。我在Unicode上看到了Ned Batchelder的演讲(https://nedbatchelder.com/text/unipain.html),并阅读了很多关于S.O的答案。但我仍然处于亏损状态。如何在python列表中编码bs4可导航字符串?
我使用Python 3和BeautifulSoup 4从维基百科中刮取并解析表。我有一个名为fighter_B
print(type(fighter_B))
<class 'list'>
print(type(fighter_B[0])
<class 'bs4.element.NavigableString'>
列表中的第二和第三观察包含与抛出一个错误,例如,法布里西奥·韦杜姆非enlgish字母名称列表。当我尝试和打印战斗机的名字,我得到这个错误,
print(fighter_B[1])
UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 4: ordinal not in range(128)
我已经试过各种编码功能,但我总是最后抛出了同样的错误。
[fighter.encode('utf-8') for fighter in fighter_B]
print(fighter_B[1])
UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 4: ordinal not in range(128)
for i in fighter_B:
i.encode('utf-8')
print(fighter_B[1])
UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 4: ordinal not in range(128)
[fighter.decode('utf-8') for fighter in fighter_B]
AttributeError: 'NavigableString' object has no attribute 'decode'
[str(fighter).decode('utf-8) for fighter in fighter_B]
AttributeError: 'str' object has no attribute 'decode'
[fighter.encode('ascii') for fighter in fighter_B]
UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 4: ordinal not in range(128)
我看到的所有各种答案都只是建议将变量编码为'utf-8'。我不知道为什么编码在这里不起作用,我想知道是否由于列表中的每个项目都是'bs4.element.NavigableString'类型。任何提示将不胜感激,因为我觉得完全在这一点上难倒。
什么是您的默认源代码?如果它是utf-8,它应该工作。 –
print(sys.getdefaultencoding())会产生“utf-8”,如果这意味着它应该工作,那么会很令人担忧 – buchmayne
您是否正在使用Python3? –