Могу ли я использовать Pywikipedia, чтобы получить только текст страницы? - PullRequest
1 голос
/ 20 июня 2009

Можно ли с помощью pywikipedia получить только текст страницы, без каких-либо внутренних ссылок или шаблонов, без картинок и т. Д .?

Ответы [ 2 ]

4 голосов
/ 21 июня 2009

Если вы имеете в виду «я хочу получить только викитекст», посмотрите на класс wikipedia.Page и метод get.

import wikipedia

site = wikipedia.getSite('en', 'wikipedia')
page = wikipedia.Page(site, 'Test')

print page.get() # '''Test''', '''TEST''' or '''Tester''' may refer to:
#==Science and technology==
#* [[Concept inventory]] - an assessment to reveal student thinking on a topic.
# ...

Таким образом, вы получите полный, сырой вики-текст из статьи.

Если вы хотите исключить синтаксис вики, как преобразовать [[Concept inventory]] в инвентарь Концепции и т. Д., Это будет немного более болезненным.

Основная причина этой проблемы заключается в том, что синтаксис вики MediaWiki не имеет определенной грамматики. Что делает его действительно трудно разобрать и раздеть. В настоящее время я не знаю программного обеспечения, которое позволяет вам делать это точно. Конечно, есть класс MediaWiki Parser, но это PHP, его немного сложно понять, и его назначение очень сильно отличается.

Но если вы хотите удалить только ссылки или очень простые вики-конструкции, используйте регулярные выражения:

text = re.sub('\[\[([^\]\|]*)\]\]', '\\1', 'Lorem ipsum [[dolor]] sit amet, consectetur adipiscing elit.')
print text #Lorem ipsum dolor sit amet, consectetur adipiscing elit.

, а затем для трубопроводных ссылок:

text = re.sub('\[\[(?:[^\]\|]*)\|([^\]\|]*)\]\]', '\\1', 'Lorem ipsum [[dolor|DOLOR]] sit amet, consectetur adipiscing elit.')
print text #Lorem ipsum DOLOR sit amet, consectetur adipiscing elit.

и т. Д.

Но, например, не существует надежного и простого способа вырезать вложенные шаблоны со страницы. И то же самое относится к изображениям, которые имеют ссылки в комментариях. Это довольно сложно и требует рекурсивного удаления самой внутренней ссылки, замены ее маркером и начала заново. Посмотрите на функцию templateWithParams в wikipedia.py, если хотите, но это не очень красиво.

1 голос
/ 05 декабря 2013

На Github есть модуль mwparserfromhell, который может приблизить вас к тому, что вы хотите, в зависимости от того, что вам нужно. У него есть метод strip_code (), который удаляет большую часть разметки.

import pywikibot
import mwparserfromhell

test_wikipedia = pywikibot.Site('en', 'test')
text = pywikibot.Page(test_wikipedia, 'Lestat_de_Lioncourt').get()

full = mwparserfromhell.parse(text)
stripped = full.strip_code()

print full
print '*******************'
print stripped

Фрагмент сравнения:

{{db-foreign}}
<!--  Commented out because image was deleted: [[Image:lestat_tom_cruise.jpg|thumb|right|[[Tom Cruise]] as Lestat in the film ''[[Interview With The Vampire: The Vampire Chronicles]]''|{{deletable image-caption|1=Friday, 11 April 2008}}]] -->

[[Image:lestat.jpg|thumb|right|[[Stuart Townsend]] as Lestat in the film ''[[Queen of the Damned (film)|Queen of the Damned]]'']]

[[Image:Lestat IWTV.jpg|thumb|right|[[Tom Cruise]] as Lestat in the 1994 film ''[[Interview with the Vampire (film)|Interview with the Vampire]]'']]

'''Lestat de Lioncourt''' is a [[fictional character]] appearing in several [[novel]]s by [[Anne Rice]], including ''[[The Vampire Lestat]]''. He is a [[vampire]] and the main character in the majority of ''[[The Vampire Chronicles]]'', narrated in first person.   

==Publication history==
Lestat de Lioncourt is the narrator and main character of the majority of the novels in Anne Rice's ''The Vampire Chronicles'' series. ''[[The Vampire Lestat]]'', the second book in the series, is presented as Lestat's autobiography, and follows his exploits from his youth in France to his early years as a vampire. Many of the other books in the series are also credited as being written by Lestat. 


*******************

thumb|right|Stuart Townsend as Lestat in the film ''Queen of the Damned''

'''Lestat de Lioncourt''' is a fictional character appearing in several novels by Anne Rice, including ''The Vampire Lestat''. He is a vampire and the main character in the majority of ''The Vampire Chronicles'', narrated in first person.   

Publication history
Lestat de Lioncourt is the narrator and main character of the majority of the novels in Anne Rice's ''The Vampire Chronicles'' series. ''The Vampire Lestat'', the second book in the series, is presented as Lestat's autobiography, and follows his exploits from his youth in France to his early years as a vampire. Many of the other books in the series are also credited as being written by Lestat. 
...