0

LinuxでPywikiBotコアバージョンを使用して、ウィキペディアページのカテゴリを簡単に取得するプログラムを作成します。私のコードは次のとおりです。

# -*- coding: utf-8  -*-
import pywikibot

site = pywikibot.Site("en")
page = pywikibot.Page(site, u"Wikipedia:Sandbox")

item = pywikibot.ItemPage.fromPage(page)
dictionary = item.get()

print page.categories

そして、私はカテゴリを取得することを期待していますが、取得します:

<bound method Page.categories of Page(Wikipedia:Sandbox)>

私はこのチュートリアルに従いますが、pywikibot のドキュメントはひどく書かれていると言うべきであり、ファイルを開いていくつかの情報を見つける必要があり、def カテゴリが見つかりました:

def categories(self, withSortKey=False, step=None, total=None,
               content=False):
    """Iterate categories that the article is in.

    @param withSortKey: if True, include the sort key in each Category.
    @param step: limit each API call to this number of pages
    @param total: iterate no more than this number of pages in total
    @param content: if True, retrieve the content of the current version
        of each category description page (default False)
    @return: a generator that yields Category objects.

    """
    return self.site.pagecategories(self, withSortKey=withSortKey,
                                    step=step, total=total, content=content)

そして、私はフレームワークのコードを変更したくありません。

4

1 に答える 1

4

これを試して:

print page.categories()

編集:

I test this before i get :<pywikibot.data.api.CategoryPageGenerator object at 0xb6c444ec> 

これは、メソッドがデータを取得する前に反復する必要があるジェネレーターを返すためです。list(page.categories()) を使用すると、ジェネレーターからリストが作成されます。

別の推奨される方法は、次のように for ループでジェネレーターを使用することです。

for category in page.categories():
    print category

ここでジェネレーターについて読むことができます:

https://wiki.python.org/moin/Generators

于 2014-05-25T14:44:23.023 に答える