Могу ли я использовать Pywikipedia, чтобы получить только текст страницы?

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

4 ответа

Если вы имеете в виду "я хочу получить только викитекст", то посмотрите на 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, если вы хотите, но это не красиво.

На 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. 

Pywikibot может удалять любые теги wikitext или html. Внутри textlib есть две функции:

  1. removeHTMLParts (text: str, keeptags=['tt', 'nowiki', 'small', 'sup']) -> str:

    Возврат текста без частей, в которых разметка HTML отключена, но сохраняет текст между тегами HTML. Например:

             from pywikibot Import textlib
     text = 'This is <small>small</small> text'
     print(removeHTMLParts(text, keeptags=[]))
    

    это напечатает:

             This is small text
    
  2. removeDisabledParts (text: str, tags=None, include=[], site=None) -> str:Вернуть текст без частей, для которых отключена вики-разметка. Это удаляет текст внутри текста викитекста. Например:

             from pywikibot Import textlib
     text = 'This is <small>small</small> text'
     print(removeDisabledPartsParts(text, tags=['small']))
    

    это напечатает:

             This is  text
    

    Есть много предопределенных тегов, которые нужно удалить или оставить, например 'comment', 'header', 'link', 'template';

    по умолчанию для тегов параметр ['comment', 'includeonly', 'nowiki', 'pre', 'syntaxhighlight']

    Еще несколько примеров:

    removeDisabledPartsParts('See [[this link]]', tags=['link']) дает 'See ' removeDisabledPartsParts('<!-- no comments -->', tags=['comment']) дает removeDisabledPartsParts('{{Infobox}}', tags=['template']) дает '', но работает только для Pywikibot 6.0.0 и выше

Вы можете использовать wikitextparser . Например:

      import pywikibot
import wikitextparser
en_wikipedia = pywikibot.Site('en', 'wikipedia')
text = pywikibot.Page(en_wikipedia,'Bla Bla Bla').get()
print(wikitextparser.parse(text).sections[0].plain_text())

даст тебе:

      "Bla Bla Bla" is a song written and recorded by Italian DJ Gigi D'Agostino. It heavily samples the vocals of "Why did you do it?" by British band Stretch. 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. It was sampled in the song "Jump" from Lupe Fiasco's 2017 album Drogas Light.
Другие вопросы по тегам