簡體   English   中英

在python中將xml DOM結構從文件轉換成字典

[英]Converting a xml DOM structure form a file into a dictionary in python

我有一個文件,實際上不是一個 xml 文件,而是一個看起來像這樣的文本文件(example.txt)-

<01-01-20>
hello hello . . random content
</01-01-20>


<04-01-20>
hello again. . some more random content.....

</04-01-20>

我想將文本文件中的值作為鍵值對存儲在字典中,例如:

{<01-01-20>:"hello hello. . ",<04-01-20>:"hello again.. . "}

這可能嗎。 請指導我如何在 python 中執行此操作

編輯 -

我想出的代碼,

import re
import mmap

tf1 = open('text1.txt', 'r+b')  ##first kosha
tf2 = open('text2.txt', 'r')  ##second kosha

first = []
second = []
reg = re.compile("^<.*>$")     ##sample regular expression for < >
for line in tf1:
    first += reg.findall(line)

for line in tf2:
    second += reg.findall(line)

print('Tags that are present in file 1 but not in file2')    
for i in first:
    if i not in second:
        print(i)




tf1.close()
tf2.close()

現在我需要比較兩個文本文件中的贊美詩並判斷它們是否相似,所以我認為最好將其放入字典中。 請幫忙。

這是您實際期望的完整代碼。

代碼

with open("file_in.txt", "r") as file:
    dict1 = {}
    lines = file.readlines()
    for i in range(len(lines)):
        try:
            if lines[i].startswith('<') and lines[i+1] != '\n':
                dict1[lines[i].strip()] = lines[i+1].strip()
        except:
            print("File read complete!")
    
print(dict1)

輸出

{'<01-01-20>': 'hello hello . . random content', '<04-01-20>': 'hello again. . some more random content.....'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM