[英]Parse multiple XML files to one list of dictionaries in Python
我有一個案例,在解析多個 XML 文件時,實際上我希望解析 XML 的結果成為單個字典列表而不是多個字典列表。
import glob
from bs4 import BeautifulSoup
def open_xml(filenames):
for filename in filenames:
with open(filename) as fp:
soup = BeautifulSoup(fp, 'html.parser')
parse_xml_files(soup)
def parse_xml_files(soup):
stringToListOfDict = []
.
.
.
for info in infos:
dict = {}
types = info.find_all('type')
values = info.find_all('value')
for type in types:
dict[type.attrs['p']] = type.text
stringToListOfDict.append({'Date': Date, 'Time': Time, 'NodeName': node})
for value in values:
for result in value.find_all('x'):
label = dict[result.attrs['y']]
value = result.text
if label:
stringToListOfDict[-1][label] = value
print(stringToListOfDict)
def main():
open_xml(filenames = glob.glob("*.xml"))
if __name__ == '__main__':
main()
使用我上面的代碼,它總是在下面生成兩個字典列表(例如,對於兩個 XML 文件):
[{'Date': '2020-11-19', 'Time': '18:15', 'NodeName': 'LinuxSuSe','Speed': '16'}]
[{'Date': '2020-11-19', 'Time': '18:30', 'NodeName': 'LinuxRedhat','Speed': '16'}]
所需的 output 應該是一個只有兩個字典的列表:
[{'Date': '2020-11-19', 'Time': '18:15', 'NodeName': 'LinuxSuSe','Speed': '16'},{'Date': '2020-11-19', 'Time': '18:30', 'NodeName':'LinuxRedhat','Speed': '16'}]
非常感謝您的反饋
print()
僅用於在屏幕上發送信息,它不會將所有結果合並到一個列表中。
您的名稱parse_xml_files
具有誤導性,因為它解析單個文件,而不是所有文件。 而這個 function 應該使用return
來發送單個文件的結果,在open_xml
你應該得到這個結果添加到一個列表中 - 然后你應該將所有文件放在一個列表中。
未測試:
def open_xml(filenames):
all_files = []
for filename in filenames:
with open(filename) as fp:
soup = BeautifulSoup(fp, 'html.parser')
result = parse_xml_file(soup) # <-- get result from parse_xml_file
all_files += result # <-- append result to list
print(all_files) # <-- display all results
def parse_xml_file(soup):
stringToListOfDict = []
# ... code ...
for info in infos:
dict = {}
types = info.find_all('type')
values = info.find_all('value')
for type in types:
dict[type.attrs['p']] = type.text
stringToListOfDict.append({'Date': Date, 'Time': Time, 'NodeName': node})
for value in values:
for result in value.find_all('x'):
label = dict[result.attrs['y']]
value = result.text
if label:
stringToListOfDict[-1][label] = value
#print(stringToListOfDict)
return stringToListOfDict # <-- send to open_xml
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.