如何使用mwclient查找维基百科页面上的修订版本之间的文本差异?

2024-04-19 17:15:25 发布

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

我正在尝试使用mwclient查找给定Wikipedia页面的两个修订版本之间的文本差异。我有以下代码:

import mwclient
import difflib

site = mwclient.Site('en.wikipedia.org')
page = site.pages['Bowdoin College']
texts = [rev for rev in page.revisions(prop='content')]
if not (texts[-1][u'*'] == texts[0][u'*']):
      ##show me the differences between the pages

谢谢你!你知道吗


Tags: the代码文本import版本pagesiterev
1条回答
网友
1楼 · 发布于 2024-04-19 17:15:25

现在还不清楚您是想要一个difflib生成的diff还是使用mwclient的mediawiki生成的diff。你知道吗

在第一种情况下,您有两个字符串(两个修订的文本),并且希望使用difflib获得差异:

...
t1 = texts[-1][u'*']
t2 = texts[0][u'*']
print('\n'.join(difflib.unified_diff(t1.splitlines(), t2.splitlines())))

(difflib还可以生成HTML diff,有关详细信息,请参阅文档。)

但是,如果您希望MediaWiki使用mwclient生成HTML diff,则需要修订ids

# TODO: Loading all revisions is slow,
# try to load only as many as required.
revisions = list(page.revisions(prop='ids'))  
last_revision_id = revisions[-1]['revid']
first_revision_id = revisions[0]['revid']

然后使用compare action比较修订ID:

compare_result = site.get('compare', fromrev=last_revision_id, torev=first_revision_id)
html_diff = compare_result['compare']['*']

相关问题 更多 >