gpt4 book ai didi

python - 在 Beautiful Soup 中寻找和存储根的子代

转载 作者:太空宇宙 更新时间:2023-11-04 00:31:26 25 4
gpt4 key购买 nike

我正在尝试查找并存储 child <orgname>来自 parent <assignee> .到目前为止,我的代码遍历 XML 文档,已经选择了某些其他标签——我已经这样设置了它:

for xml_string in separated_xml(infile): # Calls the output of the separated and read file to parse the data
soup = BeautifulSoup(xml_string, "lxml") # BeautifulSoup parses the data strings where the XML is converted to Unicode
pub_ref = soup.findAll("publication-reference") # Beginning parsing at every instance of a publication

lst = [] # Creating empty list to append into

with open('./output.csv', 'ab') as f:
writer = csv.writer(f, dialect = 'excel')

for info in pub_ref: # Looping over all instances of publication

# The final loop finds every instance of invention name, patent number, date, and country to print and append

for inv_name, pat_num, date_num, country, city, state in zip(soup.findAll("invention-title"), soup.findAll("doc-number"), assign.find("orgname"), soup.findAll("date"), soup.findAll("country"), soup.findAll("city"), soup.findAll("state")):

writer.writerow([inv_name.text, pat_num.text, org_name.text, date_num.text, country.text, city.text, state.text])

我已经有了这个顺序,所以每个发明名称和专利都配对,并且需要组织受让人名称。问题是还有其他标签与律师和此类组织相关联,如下所示:

<agent sequence="01" rep-type="attorney">
<addressbook>
<orgname>Sawyer Law Group LLP</orgname>
<address>
<country>unknown</country>
</address>
</addressbook>
</agent>
</agents>
</parties>
<assignees>
<assignee>
<addressbook>
<orgname>International Business Machines Corporation</orgname>
<role>02</role>
<address>
<city>Armonk</city>
<state>NY</state>
<country>US</country>
</address>
</addressbook>
</assignee>
</assignees>

我只想要 <assignee> 下的组织名称标签。我试过:

assign = soup.findAll("受让人")org_name = assign.findAll("组织名")

但是没有用。它只是射出:

"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key

AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?

如何添加这些标签并找到受让人标签下的所有组织名称?这看起来很简单,但我做不到。

提前致谢。

最佳答案

assign = soup.findAll("assignee")返回一个 list ,所以这就是调用 org_name = assign.findAll("orgname") 的原因失败,您必须遍历 assign 的每个元素并称之为.findAll("orgname") , 但似乎只有一个 <orgname>在每个<assignee> , 所以没有必要使用 .findAll而不是 .find .尝试使用 .find assign 的每个元素使用列表理解:

orgnames = [item.find("orgname") for item in assign]

或者,直接获取他们的文本,在 <orgname> 之前检查存在于 <assignee> 中:

orgnames = [item.find("orgname").text for item in assign if item.find("orgname")]

关于python - 在 Beautiful Soup 中寻找和存储根的子代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com