【问题标题】:Why is this returning a NoneType?为什么这会返回 NoneType?
【发布时间】:2015-08-18 05:08:51
【问题描述】:

我正在尝试使用以下函数从 Wikipedia 中获取信息,但我遇到了 属性错误,因为函数调用返回 None。有人可以尝试解释为什么这会返回 None 吗?

import wikipedia as wp
import string

def add_section_info(search):
    HTML = wp.page(search).html().encode("UTF-8") #gets HTML source from Wikipedia

    with open("temp.xml",'w') as t: #write HTML to xml format
        t.write(HTML)

    table_of_contents = []
    dict_of_section_info = {}

    #This extracts the info in the table of contents
    with open("temp.xml",'r') as r:
        for line in r:
            if "toclevel" in line: 
                new_string = line.partition("#")[2]
                content_title = new_string.partition("\"")[0]
                tbl = string.maketrans("_"," ")
                content_title = content_title.translate(tbl)
                table_of_contents.append(content_title)

    print wp.page(search).section("Aortic rupture") #this is None, but shouldn't be

    for item in table_of_contents:
        section = wp.page(search).section(item).encode("UTF-8")
        print section
        if section == "":
            continue
        else:
            dict_of_section_info[item] = section

    with open("Section_Info.txt",'a') as sect:
        sect.write(search)
        sect.write("------------------------------------------\n")
        for item in dict_of_section_info:
            sect.write(item)
            sect.write("\n\n")
            sect.write(dict_of_section_info[item])
        sect.write("####################################\n\n")

add_section_info("Abdominal aortic aneurysm")

我不明白的是,例如,如果我运行add_section_info("HIV"),它会完美运行。

导入的维基百科源代码为here

上面代码的输出是这样的:

Abdominal aortic aneurysm

Signs and symptoms
Traceback (most recent call last):
  File "/home/pharoslabsllc/Documents/wikitest.py", line 79, in <module>
add_section_info(line)
  File "/home/pharoslabsllc/Documents/wikitest.py", line 30, in add_section_info
    section = wp.page(search).section(item).encode("UTF-8")
AttributeError: 'NoneType' object has no attribute 'encode'

【问题讨论】:

  • 你能告诉我们这个错误发生在哪里吗?只需将回溯添加到问题。
  • 在失败的循环内尝试print(repr(item))
  • 你有一个硬编码的值。如果您使用print wp.page(search).section(item) 而不是print wp.page(search).section("Aortic rupture"),会发生什么?
  • 如果我打印,在 for 循环中,wp.page(search).section(item),我得到None。那是我不明白的部分-应该是文本。

标签: python wikipedia attributeerror nonetype


【解决方案1】:

page 方法永远不会返回 None(您可以在源代码中轻松查看),但是如果找不到标题,section 方法确实返回None。见documentation

section(section_title)

self.sections 获取部分的纯文本内容。 如果没有找到section_title,则返回None,否则返回一个空白字符串。

所以答案是您所指的维基百科页面没有标题为Aortic rupture 的部分,就图书馆而言

查看维基百科本身,Abdominal aortic aneurysm 页面似乎确实有这样的部分。

请注意,如果您尝试检查 wp.page(search).sections 的值,您会得到:[]。 IE。 库似乎没有正确解析这些部分。


从找到here的库的源代码可以看到这个测试:

section = u"== {} ==".format(section_title)
try:
  index = self.content.index(section) + len(section)
except ValueError:
  return None

但是:

In [14]: p.content.find('Aortic')
Out[14]: 3223

In [15]: p.content[3220:3220+50]
Out[15]: '== Aortic ruptureEdit ===\n\nThe signs and symptoms '
In [16]: p.section('Aortic ruptureEdit')
Out[16]: "The signs and symptoms of a ruptured AAA may includes severe pain in the lower back, flank, abdomen or groin. A mass that pulses with the heart beat may also be felt. The bleeding can leads to a hypovolemic shock with low blood pressure and a fast heart rate. This may lead to brief passing out.\nThe mortality of AAA rupture is up to 90%. 65–75% of patients die before they arrive at hospital and up to 90% die before they reach the operating room. The bleeding can be retroperitoneal or into the abdominal cavity. Rupture can also create a connection between the aorta and intestine or inferior vena cava. Flank ecchymosis (appearance of a bruise) is a sign of retroperitoneal bleeding, and is also called Grey Turner's sign.\nAortic aneurysm rupture may be mistaken for the pain of kidney stones, muscle related back pain."

注意Edit ==。换句话说,该库有一个错误,它没有考虑到要编辑的链接。

相同的代码适用于HIV 的页面,因为在该页面中,标题旁边没有edit 链接。我不知道为什么会这样,无论如何它看起来像是库的错误或缺点,所以你应该在它的问题跟踪器上打开一张票。

与此同时,您可以使用以下简单的修复方法:

def find_section(page, title):
    res = page.section(title)
    if res is None:
        res = page.section(title + 'Edit')
    return res

并使用此函数而不是使用.section 方法。但是,这只能是临时修复。

【讨论】:

  • 您知道为什么运行add_section_info("HIV") 会正常工作吗?因为即使是“HIV”,调用wp.page(search).sections 也会返回[ ],这就是为什么我必须这样做。
  • @MIT_noob 这是由于edit 链接,请参阅我的上次编辑。如果您检查HIV 页面,大多数标题都缺少该链接,因此该库可以正常工作。但是我不熟悉维基百科以及它们如何显示内容。我建议您在库问题跟踪器中打开一张票,因为这似乎是一个错误或未记录的缺失功能。
  • 非常感谢!快速提问:你能解释一下p.content[3220:3220+50] 的作用吗?
  • @MIT i.content 是一个包含页面文本的字符串。在那里,我简单地检查了站点Aortic出现在哪个索引处,恰好是3223,因此我使用切片检查了该索引周围的内容。 [3220:3220+50] 只是意味着将字符从3220th 带到3220+50th 一个。
【解决方案2】:

wp.page(search).section(item) 未找到您要查找的部分,并返回 None。您不检查它并尝试将值作为字符串处理;这预计会失败。

【讨论】:

    猜你喜欢
    • 2017-02-09
    • 1970-01-01
    • 2013-08-09
    • 2020-01-07
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多