所以我希望将专利数据从XML存储到CSV文件。我已经能够在发明名称,日期,国家和专利号的每次迭代中运行我的代码,但是当我尝试将结果写入CSV文件时出现问题。
XML数据看起来像这样(对于许多部分中的一部分):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE us-patent-grant SYSTEM "us-patent-grant-v42-2006-08-23.dtd" [ ]>
<us-patent-grant lang="EN" dtd-version="v4.2 2006-08-23" file="USD0584026-20090106.XML" status="PRODUCTION" id="us-patent-grant" country="US" date-produced="20081222" date-publ="20090106">
<us-bibliographic-data-grant>
<publication-reference>
<document-id>
<country>US</country>
<doc-number>D0584026</doc-number>
<kind>S1</kind>
<date>20090106</date>
</document-id>
</publication-reference>
我的代码用于逐个遍历和编写这些行:
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
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 into
with open('./output.csv', 'wb') as f:
writer = csv.writer(f, dialect = 'excel')
for inv_name, pat_num, date_num, country in zip(soup.findAll("invention-title"), soup.findAll("doc-number"), soup.findAll("date"), soup.findAll("country")):
#print(inv_name.text, pat_num.text, date_num.text, country.text)
#lst.append((inv_name.text, pat_num.text, date_num.text, country.text))
writer.writerow([inv_name.text, pat_num.text, date_num.text, country.text])
最后,我的.csv文件中的输出是:
"Content addressable information encapsulation, representation, and transfer",07475432,20090106,US
我不确定问题出在哪里,我知道我仍然是Python的新手,但是有人能找到问题吗?
答案 0 :(得分:1)
问题出在这一行with open('./output.csv', 'wb') as f:
如果要将所有行写入单个文件,请使用模式a
。使用wb
将覆盖文件,因此您只能获得最后一行。
在此处详细了解文件模式:https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
答案 1 :(得分:1)
您在循环内以覆盖模式('wb'
)打开文件。在每次迭代中,您将删除之前编写的内容。正确的方法是在循环外打开文件:
...
with open('./output.csv', 'wb') 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 into
for inv_name, pat_num, date_num, country in zip(soup.findAll("invention-title"), soup.findAll("doc-number"), soup.findAll("date"), soup.findAll("country")):
...