当标题中有一个未替换的撇号(')时,如何使用pywikibot.Page(site,title).text?

2024-09-26 22:44:54 发布

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

我有一个名为cities的字符串列表,其中每个字符串都是一个城市名称,也是维基百科页面的标题。对于每个城市,我都会看到维基百科页面,然后查看其中的文本内容:

cities = [(n["name"]) for n in graph.nodes.match("City")]
for city in cities:
       site = pywikibot.Site(code="en", fam="wikivoyage")
       page = pywikibot.Page(site, city)
       text = page.text

我列表中的一个城市是一个叫做拉奎拉的地方,它没有返回任何文本内容(而其他条目则是)。我想那是因为名字中的'。因此,我使用re.sub来转义'并传入该结果。这给了我我所期望的:

cities = [(n["name"]) for n in graph.nodes.match("City")]
city = "L'Aquila"
altered_city = re.sub("'",  "\'", city)
print(altered_city)
site = pywikibot.Site(code="en", fam="wikivoyage")
page = pywikibot.Page(site, altered_city)
print(page)
print(page.text)

结果:

[[wikivoyage:en:L'Aquila]]
{{pagebanner|Pagebanner default.jpg}}
'''L'Aquila''' is the capital of the province of the same name in the region of [[Abruzzo]] in [[Italy]] and is located in the northern part of the..

但问题是我不想硬编码城市名称,我想使用列表中的字符串。当我传入时,它不会给我任何page.text的结果:

cities = [(n["name"]) for n in graph.nodes.match("City")]
city_from_list = cities[0]
print(city_from_list)
print(type(city_from_list))
altered_city = re.sub("'",  "\'", city_from_list)
site = pywikibot.Site(code="en", fam="wikivoyage")
page = pywikibot.Page(site, altered_city)
print(page)
print(page.text)

结果:

L'Aquila
<class 'str'>
[[wikivoyage:en:L'Aquila]]

我打印了我从列表中得到的城市元素的值和类型,它是一个字符串,所以我不知道为什么它在上面工作,但在这里不工作。这些有什么不同


Tags: the字符串textincity列表pagesite
2条回答

re.sub("'", "\'", city)不做任何事情:

>>> city = "L'Aquila"
>>> re.sub("'",  "\'", city)
"L'Aquila"
>>> city == re.sub("'",  "\'", city)
True

Python将"\'"视为"'"。见文件Lexical analysis # String and Bytes literals处的表格

我不知道为什么代码的第二部分对您不起作用,但它应该起作用。也许你只是没有执行最后一行。即使page.text返回了None,print语句也应该打印None。试试print(type(page.text))

Pywikikbot按预期为拉奎拉工作:例如

>>> import pywikibot
>>> site = pywikibot.Site('wikivoyage:en')
>>> page = pywikibot.Page(site, "L'Aquila")
>>> print(page.text[:100])
{{pagebanner|Pagebanner default.jpg}}
'''L'Aquila''' is the capital of the province of the same name

似乎您的cities[0]"L'Aquila"不同。注意page.text总是给出一个str并且从不返回None。您可以使用exists()方法检查现有页面:

>>> page = pywikibot.Page(site, "L'Aquila")
>>> page.exists()
True
>>> 

相关问题 更多 >

    热门问题