首页 > 解决方案 > 为什么附加到列表会更改此数字?

问题描述

我已经为这个问题寻找了几个小时的解决方案,也浏览了这个网站上的很多帖子,但我找不到解决方案。我正在使用 python 3.9.2

from bs4 import BeautifulSoup
import requests
import re

raw_data_from_webpage = requests.get("https://en.wikipedia.org/wiki/Archimedes")
soup = BeautifulSoup(raw_data_from_webpage.content, 'html5lib')

ec14_content = str(soup.find_all("p"))
ec14_content = re.sub(r"<[^<>]*>", "", ec14_content)
ec14_content = ec14_content.split("\n, ")
ec14_info = "born"
ec14_counter = 0
ec14_answer_list = []
while ec14_counter < len(ec14_content):
    if ec14_info in ec14_content[ec14_counter]:
        ec14_looking = ec14_content[ec14_counter].replace(" c.", " circa").split(". ")
        for i in ec14_looking:
            if ec14_info in i:
                ec14_answer_list.append(i+".")
    ec14_counter += 1
print(ec14_answer_list)

print(i) = 公元前 287 年在海港城市...

print(ec14_answer_list) = \u2009287\xa0BC 在海港城市...

我真的希望有人能回答为什么会发生这种情况......

编辑:添加了最小的可重现示例。

常规数字(如“1906”)和带字母的数字(如“6th”)可以完美运行,但每当“数字”后跟“BC”或“AD”(如“287 BC”或“公元 530 年”)

我试图让我的程序阅读维基百科页面并找到答案,它做得很好,但 BC 和 AD 年份显示为“\u2009”+number+“\xa0”+BC。

我尝试用“”替换“\u2009”(和“\u2009”),但这并没有做任何事情......

标签: python-3.x

解决方案


问题在于您的环境中的文件编码。\u2009 是薄空间的 unicode 符号,如下所示:

import unicodedata
print(unicodedata.name('\u2009'))
#THIN SPACE

确保在您使用的任何环境中检查编码。在我使用 UTF-8 的环境中,我在使用您的代码时没有发现任何问题:

i = "287 BC in the seaport city"
ec14_answer_list = []
ec14_answer_list.append(i+".")
print(ec14_answer_list)
#['287 BC in the seaport city.']

另一种可能性是您的原始字符串 i 编码不正确。尝试清理或重写 i。


推荐阅读