【发布时间】:2022-01-26 01:31:55
【问题描述】:
我正在尝试解析多个(最终超过 1000 个)xml 文件以获取三个信息 persName、@ref 和 /date。我设法获取了所有文件,当我使用 print() 时,它为我提供了我想要的所有信息。但是,当我尝试将该信息写入 csv 文件时,只会解析最后一个 xml 文件。
from bs4 import BeautifulSoup
import csv
import os
path = r'C:\programming1\my-app'
for filename in os.listdir(path):
if filename.endswith(".xml"):
fullpath = os.path.join(path, filename)
f = csv.writer(open("test2.csv", "w"))
f.writerow(["date", "Name", "pref"])
soup = BeautifulSoup (open(fullpath, encoding="utf-8"), "lxml")
# removing unnecessary information to better isolate //date
for docs in soup.find_all('tei'):
for pubstmt in soup.find_all("publicationStmt"):
pubstmt.decompose()
for sourdesc in soup.find_all("sourceDesc"):
sourdesc.decompose()
for lists in soup.find_all("list"):
lists.decompose()
for heads in soup.find_all("head"):
lists.decompose()
#finding all dates of Protokolls under /title
for dates in soup.find_all("date"):
date = dates.get('when')
#getting all Names from xml files exept for thos in /list
for Names in soup.find_all("persname"):
nameonly = Names.contents
nameref = Names.get("ref")
f.writerow([date, nameonly, nameref])'
如果我把 writerow 放在 Names 下面,那么它只会写入最后一个文件的所有信息,如果我把 writerow 放在 Names 后面,那么它只会写入一个名字的信息
谁能告诉我我做错了什么?我尝试了很多 for 循环,但似乎都没有。
【问题讨论】:
-
您最好使用xml parser。
-
open("test2.csv", "w")表示打开覆盖。改用"a"追加 -
你能做到吗?
-
@ZachYoung 这确实很好地解决了问题。我确实最终选择了“尝试”循环,因为它看起来更有条理
标签: python xml csv parsing beautifulsoup