如何从维基百科中获取纯文本

时间:2010-12-15 16:09:23

标签: python-3.x mediawiki wikipedia wikipedia-api mediawiki-api

我一直在寻找大约2个月的时间来找到一个仅获得维基百科描述部分的脚本。 (这是我正在建造的机器人,不适用于IRC。)也就是说,当我说

/wiki bla bla bla

它将转到Wikipedia page for bla bla bla,获取以下内容,然后将其返回聊天室:

   Bla Bla Bla是一首歌的名字   由Gigi D'Agostino制作。他描述道   这首歌是“我写的一首思想   所有谈话和谈话的人   没有说什么“   突出但无意义的声乐   样品取自英国乐队   Stretch的歌曲“你为什么这么做”

这是我找到的最接近的,但它只获取网址:

import json
import urllib.request, urllib.parse

def google(searchfor):
  query = urllib.parse.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query

  search_response = urllib.request.urlopen(url)
  search_results = search_response.read().decode("utf8")
  results = json.loads(search_results)
  data = results['responseData']
  hits = data['results']

  if len(hits) > 0:
    return hits[0]['url']
  else:
    return "No results found."

(Python 3.1)

12 个答案:

答案 0 :(得分:17)

使用在维基百科上运行的MediaWiki API。您必须自己解析一些数据。

例如:

  

http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&&titles=Bla%20Bla%20Bla

means

  

以JSON格式(格式= json)fetch(action = query)最新版主页面(title = Main%20Page)的内容(rvprop = content)。

您可能希望搜索查询并使用第一个结果来处理拼写错误等。

答案 1 :(得分:12)

以下是一些不同的可能方法;使用适合你的那个。我下面的所有代码示例都使用requests来获取对API的HTTP请求;如果你有Pip,你可以用requests安装pip install requests。他们也都使用Mediawiki API,两个使用query端点;如果您需要文档,请按照这些链接。

1。获取整个页面或页面的纯文本表示" extract"直接来自API extracts prop

请注意,此方法仅适用于TextExtracts extension的MediaWiki网站。这尤其包括维基百科,但不包括像http://www.wikia.com/

这样的较小的Mediawiki网站

您想要点击

这样的网址

https://en.wikipedia.org/w/api.php?action=query&format=json&titles=Bla_Bla_Bla&prop=extracts&exintro&explaintext

打破这种局面,我们在那里得到了以下参数(记录在https://www.mediawiki.org/wiki/Extension:TextExtracts#query+extracts):

  • action=queryformat=jsontitle=Bla_Bla_Bla都是标准的MediaWiki API参数
  • prop=extracts让我们使用TextExtracts扩展
  • exintro限制对第一部分标题
  • 之前的内容的响应
  • explaintext使回复中的摘录为纯文本而非HTML

然后解析JSON响应并提取提取:

>>> import requests
>>> response = requests.get(
...     'https://en.wikipedia.org/w/api.php',
...     params={
...         'action': 'query',
...         'format': 'json',
...         'titles': 'Bla Bla Bla',
...         'prop': 'extracts',
...         'exintro': True,
...         'explaintext': True,
...     }
... ).json()
>>> page = next(iter(response['query']['pages'].values()))
>>> print(page['extract'])
"Bla Bla Bla" is the title of a song written and recorded by Italian DJ Gigi D'Agostino. It was released in May 1999 as the third single from the album, L'Amour Toujours. It reached number 3 in Austria and number 15 in France. This song can also be heard in an added remixed mashup with L'Amour Toujours (I'll Fly With You) in its US radio version.

2。使用parse端点获取页面的完整HTML,解析它,并提取第一段

MediaWiki有一个parse endpoint,您可以点击https://en.wikipedia.org/w/api.php?action=parse&page=Bla_Bla_Bla之类的网址来获取网页的HTML。然后,您可以使用lxml之类的HTML解析器对其进行解析(首先使用pip install lxml安装)以提取第一段。

例如:

>>> import requests
>>> from lxml import html
>>> response = requests.get(
...     'https://en.wikipedia.org/w/api.php',
...     params={
...         'action': 'parse',
...         'page': 'Bla Bla Bla',
...         'format': 'json',
...     }
... ).json()
>>> raw_html = response['parse']['text']['*']
>>> document = html.document_fromstring(raw_html)
>>> first_p = document.xpath('//p')[0]
>>> intro_text = first_p.text_content()
>>> print(intro_text)
"Bla Bla Bla" is the title of a song written and recorded by Italian DJ Gigi D'Agostino. It was released in May 1999 as the third single from the album, L'Amour Toujours. It reached number 3 in Austria and number 15 in France. This song can also be heard in an added remixed mashup with L'Amour Toujours (I'll Fly With You) in its US radio version.

3。自己解析wiki文件

您可以使用query API获取网页的wikitext,使用mwparserfromhell进行解析(先使用pip install mwparserfromhell安装),然后将其缩小为人工 - 使用strip_code的可读文本。 strip_code在撰写本文时并不完美(在下面的示例中清楚地显示),但希望能够改进。

>>> import requests
>>> import mwparserfromhell
>>> response = requests.get(
...     'https://en.wikipedia.org/w/api.php',
...     params={
...         'action': 'query',
...         'format': 'json',
...         'titles': 'Bla Bla Bla',
...         'prop': 'revisions',
...         'rvprop': 'content',
...     }
... ).json()
>>> page = next(iter(response['query']['pages'].values()))
>>> wikicode = page['revisions'][0]['*']
>>> parsed_wikicode = mwparserfromhell.parse(wikicode)
>>> print(parsed_wikicode.strip_code())
{{dablink|For Ke$ha's song, see Blah Blah Blah (song). For other uses, see Blah (disambiguation)}}

"Bla Bla Bla" is the title of a song written and recorded by Italian DJ Gigi D'Agostino. It was released in May 1999 as the third single from the album, L'Amour Toujours. It reached number 3 in Austria and number 15 in France. This song can also be heard in an added remixed mashup with L'Amour Toujours (I'll Fly With You) in its US radio version.

Background and writing
He described this song as "a piece I wrote thinking of all the people who talk and talk without saying anything". The prominent but nonsensical vocal samples are taken from UK band Stretch's song "Why Did You Do It"''.

Music video
The song also featured a popular music video in the style of La Linea. The music video shows a man with a floating head and no arms walking toward what appears to be a shark that multiplies itself and can change direction. This style was also used in "The Riddle", another song by Gigi D'Agostino, originally from British singer Nik Kershaw.

Chart performance
Chart (1999-00)PeakpositionIreland (IRMA)Search for Irish peaks23

References

External links


Category:1999 singles
Category:Gigi D'Agostino songs
Category:1999 songs
Category:ZYX Music singles
Category:Songs written by Gigi D'Agostino

答案 2 :(得分:7)

您可以使用API​​获取第一部分:

http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvsection=0&titles=Bla%20Bla%20Bla&rvprop=content

这将为您提供原始wiki文本,您将不得不处理模板和标记。

或者您可以将整个页面呈现为HTML,这在解析方面有其自身的优缺点:

http://en.wikipedia.org/w/api.php?action=parse&prop=text&page=Bla_Bla_Bla

我看不到一个简单的方法来在单个调用中获取第一部分的HTML,但是您可以通过传递从第一个URL收到的wikitext并使用text=来实现两个调用第二个网址中的page=

<强>更新

抱歉,我忽略了你问题的“纯文本”部分。获取您想要的文章的一部分作为HTML。剥离HTML比剥离wikitext更容易

答案 3 :(得分:7)

您可以使用文字格式获取维基数据。如果您需要访问许多标题的信息,您可以通过一次调用获得所有标题的维基数据。使用竖线字符(|)分隔每个标题。

http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Yahoo|Google&redirects=

此api调用返回Googles和Yahoos数据。

explaintext =&gt;将提取返回为纯文本而不是有限的HTML。

exlimit = max(现为20岁);否则只会返回一个结果。

exintro =&gt;仅返回第一部分之前的内容。如果您想要完整数据,请将其删除。

redirects=解决重定向问题。

答案 4 :(得分:4)

DBPedia是解决此问题的完美解决方案。在这里:http://dbpedia.org/page/Metallica,使用RDF查看完美组织的数据。可以使用SPARQL(RDF的查询语言)在http://dbpedia.org/sparql查询此处的任何内容。总有办法找到pageID以获取描述性文字,但这应该在大多数情况下都可以。

对于编写任何有用的代码,RDF和SPARQL都会有一个学习曲线,但这是一个完美的解决方案。

例如,为Metallica运行的查询返回一个HTML表格,其中包含几种不同语言的摘要:

<table class="sparql" border="1">
  <tr>
    <th>abstract</th>
  </tr>
  <tr>
    <td><pre>"Metallica is an American heavy metal band formed..."@en</pre></td>
  </tr>
  <tr>
    <td><pre>"Metallica es una banda de thrash metal estadounidense..."@es</pre></td>
... 

SPARQL QUERY:

PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
PREFIX dbpprop: <http://dbpedia.org/property/>
PREFIX dbres: <http://dbpedia.org/resource/>

SELECT ?abstract WHERE {
 dbres:Metallica dbpedia-owl:abstract ?abstract.
}

改变&#34; Metallica&#34;对于与abstract有关的查询的任何资源名称(资源名称,如wikipedia.org/resourcename)。

答案 5 :(得分:1)

我认为更好的选择是使用为您提供MediaWiki API的 extracts道具。它只返回一些标签(b,i,h#,span,ul,li)并删除表格,信息框,引用等。

http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Bla%20Bla%20Bla&format=xml 给你一些非常简单的东西:

<api><query><pages><page pageid="4456737" ns="0" title="Bla Bla Bla"><extract xml:space="preserve">
<p>"<b>Bla Bla Bla</b>" is the title of a song written and recorded by Italian DJ Gigi D'Agostino. It was released in May 1999 as the third single from the album, <i>L'Amour Toujours</i>. It reached number 3 in Austria and number 15 in France. This song can also be heard in an added remixed mashup with <i>L'Amour Toujours (I'll Fly With You)</i> in its US radio version.</p> <p></p> <h2><span id="Background_and_writing">Background and writing</span></h2> <p>He described this song as "a piece I wrote thinking of all the people who talk and talk without saying anything". The prominent but nonsensical vocal samples are taken from UK band Stretch's song <i>"Why Did You Do It"</i>.</p> <h2><span id="Music_video">Music video</span></h2> <p>The song also featured a popular music video in the style of La Linea. The music video shows a man with a floating head and no arms walking toward what appears to be a shark that multiplies itself and can change direction. This style was also used in "The Riddle", another song by Gigi D'Agostino, originally from British singer Nik Kershaw.</p> <h2><span id="Chart_performance">Chart performance</span></h2> <h2><span id="References">References</span></h2> <h2><span id="External_links">External links</span></h2> <ul><li>Full lyrics of this song at MetroLyrics</li> </ul>
</extract></page></pages></query></api>

然后你可以通过正则表达式运行它,在JavaScript中会是这样的(也许你需要做一些小修改:

/^.*<\s*extract[^>]*\s*>\s*((?:[^<]*|<\s*\/?\s*[^>hH][^>]*\s*>)*).*<\s*(?:h|H).*$/.exec(data)

它给你(只有paragrphs,粗体和斜体):

Bla Bla Bla ”是由意大利DJ Gigi D'Agostino编写和录制的歌曲的标题。它于1999年5月发行,作为专辑 L'Amour Toujours 的第三首单曲。它在奥地利排名第3,在法国排名第15。这首歌也可以在其美国电台版本中与 L'Amour Toujours(我会随你飞)添加混合混搭。

答案 6 :(得分:0)

“......仅获取维基百科描述部分的脚本......”

对于您的应用程序,您可以查看转储上的内容,例如:http://dumps.wikimedia.org/enwiki/20120702/

您需要的特定文件是“抽象”XML文件,例如,这个小文件(22.7MB):

http://dumps.wikimedia.org/enwiki/20120702/enwiki-20120702-abstract19.xml

XML有一个名为'abstract'的标签,其中包含每篇文章的第一部分。

否则wikipedia2text使用例如w3m来下载扩展并格式化为文本的模板的页面。从那里你可以通过正则表达式来挑选摘要。

答案 7 :(得分:0)

您可以尝试使用WikiExtractor:http://medialab.di.unipi.it/wiki/Wikipedia_Extractor

适用于Python 2.7和3.3 +。

答案 8 :(得分:0)

首先检查here

MediaWiki的文本标记中存在大量无效语法。 (用户犯的错误......) 只有MediaWiki可以解析这个地狱般的文本。 但仍有一些替代方法可以尝试上面的链接。 不完美,但总比没有好!

答案 9 :(得分:0)

或者,您可以尝试像这样简单地加载Wiki页面的任何文本 https://bn.wikipedia.org/w/index.php?title=User:ShohagS&action=raw&ctype=text

bn更改为您的Wiki语言,并将User:ShohagS更改为页面名称。在您的情况下使用: https://en.wikipedia.org/w/index.php?title=Bla_bla_bla&action=raw&ctype=text

在浏览器中,这将返回一个php格式的文本文件。

答案 10 :(得分:-1)

您可以为python尝试BeautifulSoup HTML解析库,但是您必须编写一个简单的解析器。

答案 11 :(得分:-1)

还有机会通过像JSONpedia这样的包装器API来使用维基百科页面,它既可以实时工作(请求维基页面的当前JSON表示),也可以基于存储工作(查询以前在Elasticsearch中提取的多个页面)和MongoDB)。 输出JSON还包括纯文本呈现的页面文本。