![](/img/trans.png)
[英]Need to Replace Element value with Mix Content with lxml etree Python
[英]Python replace XML content with Etree
我想使用Python Etree解析器來解析和比較2個XML文件,如下所示:
我有2個XML文件,其中包含大量數據。 一種是英語(源文件),另一種是相應的法文翻譯(目標文件)。 例如:
源文件:
<AB>
<CD/>
<EF>
<GH>
<id>123</id>
<IJ>xyz</IJ>
<KL>DOG</KL>
<MN>dogs/dog</MN>
some more tags and info on same level
<metadata>
<entry>
<cl>Translation</cl>
<cl>English:dog/dogs</cl>
</entry>
<entry>
<string>blabla</string>
<string>blabla</string>
</entry>
some more strings and entries
</metadata>
</GH>
</EF>
<stuff/>
<morestuff/>
<otherstuff/>
<stuffstuff/>
<blubb/>
<bla/>
<blubbbla>8</blubbla>
</AB>
目標文件看起來完全一樣,但是在某些地方沒有文本:
<MN>chiens/chien</MN>
some more tags and info on same level
<metadata>
<entry>
<cl>Translation</cl>
<cl></cl>
</entry>
法語目標文件有一個空的跨語言引用,每當兩個宏具有相同的ID時,我要在其中引用英語源文件中的信息。 我已經寫了一些代碼,其中用唯一的標簽名替換了字符串標簽名,以便識別跨語言引用。 現在,我想比較2個文件,如果2個宏具有相同的ID,則將法語文件中的空引用與英語文件中的信息進行交換。 我之前曾嘗試過minipar解析器,但遇到了麻煩,現在想嘗試Etree。 我對編程幾乎一無所知,並且很難做到這一點。 這是我到目前為止的代碼:
macros = ElementTree.parse(english)
for tag in macros.getchildren('macro'):
id_ = tag.find('id')
data = tag.find('cl')
id_dict[id_.text] = data.text
macros = ElementTree.parse(french)
for tag in macros.getchildren('macro'):
id_ = tag.find('id')
target = tag.find('cl')
if target.text.strip() == '':
target.text = id_dict[id_.text]
print (ElementTree.tostring(macros))
我絕不知情,閱讀有關此內容的其他文章更使我感到困惑。 如果有人能啟發我,我將非常感激:-)
可能還有更多細節需要澄清。 這是帶有一些調試打印的樣本,它說明了這一想法。 它假定兩個文件具有完全相同的結構,並且您只想在根目錄下一層:
import xml.etree.ElementTree as etree
english_tree = etree.parse('en.xml')
french_tree = etree.parse('fr.xml')
# Get the root elements, as they support iteration
# through their children (direct descendants)
english_root = english_tree.getroot()
french_root = french_tree.getroot()
# Iterate through the direct descendants of the root
# elements in both trees in parallel.
for en, fr in zip(english_root, french_root):
assert en.tag == fr.tag # check for the same structure
if en.tag == 'id':
assert en.text == fr.text # check for the same id
elif en.tag == 'string':
if fr.text is None:
fr.text = en.text
print en.text # displaying what was replaced
etree.dump(french_tree)
對於文件的更復雜的結構,可以通過遍歷樹中所有元素的方式來替換通過節點的直接子級構成的循環。 如果文件的結構完全相同,則以下代碼將起作用:
import xml.etree.ElementTree as etree
english_tree = etree.parse('en.xml')
french_tree = etree.parse('fr.xml')
for en, fr in zip(english_tree.iter(), french_tree.iter()):
assert en.tag == fr.tag # check if the structure is the same
if en.tag == 'id':
assert en.text == fr.text # identification must be the same
elif en.tag == 'string':
if fr.text is None:
fr.text = en.text
print en.text # display the inserted text
# Write the result to the output file.
with open('fr2.xml', 'w') as fout:
fout.write(etree.tostring(french_tree.getroot()))
但是,它僅在兩個文件具有完全相同的結構時才起作用。 讓我們遵循在手動完成任務時將使用的算法。 首先,我們需要找到空白的法語翻譯。 然后,應使用具有相同標識的GH元素的英文翻譯替換它。 搜索元素時,將使用XPath表達式的子集:
import xml.etree.ElementTree as etree
def find_translation(tree, id_):
# Search fot the GH element with the given identification, and return
# its translation if found. Otherwise None is returned implicitly.
for gh in tree.iter('GH'):
id_elem = gh.find('./id')
if id_ == id_elem.text:
# The related GH element found.
# Find metadata entry, extract the translation.
# Warning! This is simplification for the fixed position
# of the Translation entry.
me = gh.find('./metadata/entry')
assert len(me) == 2 # metadata/entry has two elements
cl1 = me[0]
assert cl1.text == 'Translation'
cl2 = me[1]
return cl2.text
# Body of the program. --------------------------------------------------
english_tree = etree.parse('en.xml')
french_tree = etree.parse('fr.xml')
for gh in french_tree.iter('GH'): # iterate through the GH elements only
# Get the identification of the GH section
id_elem = gh.find('./id')
id_ = id_elem.text
# Find and check the metadata entry, extract the French translation.
# Warning! This is simplification for the fixed position of the Translation
# entry.
me = gh.find('./metadata/entry')
assert len(me) == 2 # metadata/entry has two elements
cl1 = me[0]
assert cl1.text == 'Translation'
cl2 = me[1]
fr_translation = cl2.text
# If the French translation is empty, put there the English translation
# from the related element.
if cl2.text is None:
cl2.text = find_translation(english_tree, id_)
with open('fr2.xml', 'w') as fout:
fout.write(etree.tostring(french_tree.getroot()).decode('utf-8'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.