我正在嘗試決議多個(最終超過 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 回圈,但似乎都不起作用。
uj5u.com熱心網友回復:
你寫了:
但是,當我嘗試將該資訊寫入 csv 檔案時,只會決議最后一個 xml 檔案。
通過閱讀您的代碼,發生的事情是:
決議每個 XML,但僅將最后一個 XML 檔案寫入 CSV
那是因為您正在為每個輸入 XML打開test2.csv “用于寫入”。當您打開寫入時"w",它會創建檔案,或者在您的情況下,它會為每次迭代重新創建檔案(覆寫其內容)。
因為你想要一個標題:
- 在開始迭代 XML 之前,您需要打開 CSV
- 寫你的標題
- 回圈處理您的 XML 處理并寫入 CSV
- 在最底部,退出回圈后,關閉 CSV
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/401943.html
