如何使用维基百科 API 获取位置查询(国家或 state/province and/or 县)的人口?

How to get the population of a location query (country or state/province and/or county) using wikipedia API?

我正在尝试使用 Covid-19 Dataset to build an SIR model. In order to build this model, I require the population of each location (country or province/state and/or county) to calculate the S (susceptible) in SIR. Since this dataset does not contain population data, I thought it would be good to do this using an API. I came across countryinfo, but the population estimates have not been updated since 2018 (according to the example and pypi);此外,输入国家名称时必须小心,因为 countryinfo 接受的名称不一定与数据集中提供的名称相同。

from countryinfo import CountryInfo

country = CountryInfo('Singapore')
p = country.population()
print(p)
# 5469700

country = CountryInfo('United States')
# country = CountryInfo('US') # is not accepted
p = country.population()
print(p)
# 319259000

我可以在 google 中键入通用查询(即键入 "US""United States")以查找任何位置的人口,但我不确定如何以编程方式执行此操作在 python。在下面输入 'us' 代替 location 将显示美国人口(通过 this solution)。

query = 'https://www.google.com/search?q=' + location + 'population

我认为 wikipedia API 可以达到同样的效果,但我不太确定如何做到这一点。有没有更好的办法?如果没有,我如何使用 wikipedia 从查询位置获取人口?

正如 smartse 提到的,使用维基数据比使用维基百科更容易解决这个问题。在维基百科上,信息不是以结构化的方式存储的,因此您无法编写查询来直接获取人口。您必须使用 API 调用来加载关于该地点的文章,然后使用您自己的代码解析文本以检索人口。

要查询维基数据,您可以使用Wikidata Query Service。 首先执行给定关键字搜索然后 returns 结果填充的查询如下

SELECT ?population WHERE {
  SERVICE wikibase:mwapi {
      bd:serviceParam mwapi:search "Singapore" .    
      bd:serviceParam mwapi:language "en" .    
      bd:serviceParam wikibase:api "EntitySearch" .
      bd:serviceParam wikibase:endpoint "www.wikidata.org" .
      bd:serviceParam wikibase:limit 1 .
      ?item wikibase:apiOutputItem mwapi:item .
  }
  ?item wdt:P1082 ?population
}

请注意,维基数据中的数据有时也会过时。但是由于从一年到下一年人口不会发生显着变化,因此这对您的应用程序来说应该不是问题。