0

テキスト ファイルを解析するときに、xml ツリーに二重ブランチを作成しないようにする必要があります。テキストファイルが次のようになっているとします (行の順序はランダムです)。

branch1:branch11:message11
branch1:branch12:message12
branch2:branch21:message21
branch2:branch22:message22

したがって、結果の xml ツリーには、2 つのブランチを持つルートが必要です。これらのブランチには両方とも 2 つのサブブランチがあります。このテキスト ファイルを解析するために使用する Python コードは次のとおりです。

import string
fh = open ('xmlbasic.txt', 'r')
allLines = fh.readlines()
fh.close()
import xml.etree.ElementTree as ET
root = ET.Element('root')

for line in allLines:
   tempv = line.split(':')
   branch1 = ET.SubElement(root, tempv[0])
   branch2 = ET.SubElement(branch1, tempv[1])
   branch2.text = tempv[2]

tree = ET.ElementTree(root)
tree.write('xmlbasictree.xml')

このコードの問題は、テキストファイルの各行で xml ツリーのブランチが作成されることです。

この名前のブランチが既に存在する場合、xml ツリーに別のブランチを作成しないようにする方法はありますか?

4

2 に答える 2

1
with open("xmlbasic.txt") as lines_file:
    lines = lines_file.read()

import xml.etree.ElementTree as ET

root = ET.Element('root')

for line in lines:
    head, subhead, tail = line.split(":")

    head_branch = root.find(head)
    if not head_branch:
        head_branch = ET.SubElement(root, head)

    subhead_branch = head_branch.find(subhead)
    if not subhead_branch:
        subhead_branch = ET.SubElement(branch1, subhead)

    subhead_branch.text = tail

tree = ET.ElementTree(root)
ET.dump(tree)

ロジックは単純です。質問で既に述べています。ブランチを作成する前に、ブランチがすでにツリーに存在するかどうかを確認する必要があるだけです。

各行ごとにツリー全体を検索するため、これはおそらく非効率的であることに注意してください。これはElementTree、独自性を考慮して設計されていないためです。


速度が必要な場合 (特に小さいツリーの場合は必要ない場合があります)、より効率的な方法は、 を使用しdefaultdictてツリー構造を格納してから に変換することElementTreeです。

import collections
import xml.etree.ElementTree as ET

with open("xmlbasic.txt") as lines_file:
    lines = lines_file.read()

root_dict = collections.defaultdict( dict )
for line in lines:
    head, subhead, tail = line.split(":")
    root_dict[head][subhead] = tail

root = ET.Element('root')
for head, branch in root_dict.items():
    head_element = ET.SubElement(root, head)
    for subhead, tail in branch.items():
        ET.SubElement(head_element,subhead).text = tail

tree = ET.ElementTree(root)
ET.dump(tree)
于 2010-09-21T10:30:40.897 に答える
0

これらの線に沿って何か?辞書で再利用するブランチのレベルを保持します。

b1map = {}

for line in allLines:
   tempv = line.split(':')
   branch1 = b1map.get(tempv[0])
   if branch1 is None:
       branch1 = b1map[tempv[0]] = ET.SubElement(root, tempv[0])
   branch2 = ET.SubElement(branch1, tempv[1])
   branch2.text = tempv[2]
于 2010-09-21T10:13:07.477 に答える