【问题标题】:AttributeError: 'NoneType' object has no attribute 'encode' with lxml-pythonAttributeError:“NoneType”对象没有使用 lxml-python 的“编码”属性
【发布时间】:2012-04-12 10:13:39
【问题描述】:

我在解析一些 XML 专利发明人数据时收到 AttributeError: 'NoneType' object has no attribute 'encode' 错误。我正在尝试将第一个发明者加上他们的地址信息拉成一个字符串,如下所示:

inventor1 = first(doc.xpath('//applicants/applicant/addressbook/last-name/text()'))
inventor2 = first(doc.xpath('//applicants/applicant/addressbook/first-name/text()'))
inventor3 = first(doc.xpath('//applicants/applicant/addressbook/address/city/text()'))
inventor4 = first(doc.xpath('//applicants/applicant/addressbook/address/state/text()'))
inventor5 = first(doc.xpath('//applicants/applicant/addressbook/address/country/text()'))
inventor = str(inventor2.encode("UTF-8")) + " " + str(inventor1.encode("UTF-8"))
inventors2 = str(inventor3.encode("UTF-8")) + ", " + str(inventor4) + ", " + str(inventor5)
inventors = str(inventor) + ", " + str(inventors2)

print "DocID: {0}\nGrantDate: {1}\nApplicationDate: {2}\nNumber of Claims: {3}\nExaminers: {4}\nAssignee: {5}\nInventor: {6}\n".format(docID,grantdate,applicationdate,claimsNum,examiners.encode("UTF-8"),assignees,inventors)

但存在问题,因为在这个长 xml 中有多个部分的 UnicodeEncodeError: 'ascii' codec can't encode character。我需要在我的 python 中有.encodes,所以我不会产生错误,但这样做我得到了这个:

Traceback (most recent call last):
  File "C:\Documents and Settings\Desktop\FINAL BART INFO ONE.py", line 87, in <module> inventor = str(inventor2.encode("UTF-8")) + " " + str(inventor1.encode("UTF-8"))
AttributeError: 'NoneType' object has no attribute 'encode'

是否有忽略在什么都没有时返回的“无”值?我必须def 还是为我的print 使用不同类型的.encode?

顺便说一句,我从输入文件创建数据库实际上是将多个 XML 文件附加到一个文件。 (数据文件来源于Google Patents)。

【问题讨论】:

    标签: python string lxml encode nonetype


    【解决方案1】:

    你总是可以做快速而肮脏的str(inventor1.encode("UTF-8") if inventor1 else inventor1)

    【讨论】:

    • 我在下一行是 inventors2 = str(inventor3.encode("UTF-8")) + ", " + str(inventor4) 出错了。我可以把你的建议放在str(inventor4 if inventor4 else inventor4) 中吗?这行得通吗?
    • 好吧,这没有任何意义,因为你会说 a if a else a 并且总是得到 a。如果 x 和 z 不同,则只有一个指向 x 如果 y 否则 z 。无论如何,下一行的问题不是发明人4,我敢打赌,它是发明人2上的相同编码调用。为此,您可以再次使用 x if y else z 东西。不过,这里更大的问题是为什么你不只是在某种循环中做这一切。
    • 嘿你的权利 - 我让它工作。我只是把它们放在 .encodes 上,就像你对inventors2 所说的那样。我这样做的原因是 A)我的老板希望我以这种方式生成数据,以便他能够理解 B)我对 python 的了解也有限,这种方法虽然粗糙,但可以让我收集我解析时需要的一切。感谢您的有用回答 +1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2017-10-05
    • 2018-03-17
    • 2019-01-10
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多