我正在尝试使用 mwclient 查找给定维基百科页面的两个修订版之间的文本差异。我有以下代码:
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
谢谢!
最佳答案
目前尚不清楚您是否想要使用 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 差异,请参阅文档以获取更多信息。)
但是,如果您想要使用 mwclient
生成 MediaWiki 生成的 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']['*']
关于python - 如何使用 mwclient 查找维基百科页面上修订版之间的文本差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52283962/