【问题标题】:Why pywikibot give <bound method Page.categories of Page(Wikipedia:Sandbox)> in out put?为什么pywikibot在输出中给出<bound method Page.categories of Page(Wikipedia:Sandbox)>?
【发布时间】:2014-05-25 14:40:39
【问题描述】:

我在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)>

我关注this tutorial,但我应该说 pywikibot 中的文档写得不好,你应该打开文件查找一些信息,我发现 def categories:

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)

而且我不喜欢更改框架代码。

【问题讨论】:

    标签: python pywikibot


    【解决方案1】:

    试试这个:

    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

    【讨论】:

    • 我在得到: 之前对此进行了测试
    • 尝试打印 list(page.categories()) 或在 for 循环中使用它,for page in page.categories(): print page
    • list 给我 [Category(Category:Wikipedia editing aids)] 我认为这是我需要的,但是你能解释一下为什么并在你的答案中编辑它让我接受它。
    猜你喜欢
    • 2015-07-06
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 2014-05-27
    相关资源
    最近更新 更多