![](/img/trans.png)
[英]How to search and replace text from one file to another using Python?
[英]How to search and replace text in an XML file using Python?
如何在整個xml文件中搜索特定的文本模式,然后在Python 3.5中用新的文本模式替換該文本的每次出現?
其他所有內容(格式,屬性,注釋等)都需要保留在原始xml文件中。
我在Windows(win32)上運行Python 3.5.1。
具體來說,我想將每次出現的“功能名稱”替換為“此工作”,並將每次出現的“功能號”替換為“ 12345”。
我一直在嘗試學習Python和xml.etree.ElementTree,但無法弄清楚。 我已經看過“在Python中搜索並替換.xml文件中的行”,“在Python中搜索並替換文件中的行”以及“如何使用Python搜索並替換文件中的文本?”。 以及該站點上其他現有的Q / A,但無法弄清楚-我不是一位經驗豐富的程序員,所以請告訴我是否需要更多輸入。 非常感謝您的幫助!!!
這是當我在記事本中打開xml代碼時的樣子的副本(除了我添加空格以使每行縮進並在將其粘貼到此問題中時打了回車符)之外:
<description-topic>
<access-info>
<index-term-set>
<index-term>
<primary>FID FEATURE NUMBER</primary>
</index-term>
<index-term>
<primary>FEATURE NAME</primary>
</index-term>
<index-term>
<primary>Common features</primary>
<secondary>FID FEATURE NUMBER</secondary>
</index-term>
</index-term-set>
</access-info>
<title>FEATURE NUMBER - FEATURE NAME</title>
<block>
<label>Platform</label>
<comment>REVIEWERS: I guessed at the FEATURE NAME</comment>
<para>
This feature applies to the following platforms: FEATURE NAME<!--Check the values--></para>
</block>
<block branch="no">
<label>Feature Benefits</label>
<para>
<comment>REVIEWERS: What do we put here? See template (link given in review email) for more information.</comment>
</para>
</block>
<block branch="no">
<label>Dependencies</label>
<para/>
<subblock>
<label>Features</label>
<comment>What FEATURE NAME do we put here?</comment>
</subblock>
<subblock>
<label>Hardware</label>
<comment>What FEATURE NAME do we put here?</comment>
<para>This feature applies to the following: FEATURE NUMBER and text.</para><?Pub Caret -1?>
</subblock>
<subblock>
<label>Dependencies outside the eNodeB</label>
<comment>What FEATURE NAME do we put here?</comment>
</subblock>
</block>
<block branch="no">
<label>Impacts</label>
<comment>REVIEWERS: What FEATURE NUMBER do we put here?</comment>
<para>
<comment/>
</para>
</block>
</description-topic>
這是我嘗試使用的最新代碼:
from xml.etree import ElementTree as et
tree = et.parse('Atemplate2.xml')
tree.find('description-topic/access-info/index-term-set/index-term/primary/').text = '12345'
tree.write('Atemplate2.xml')
我收到以下錯誤:追溯(最近一次呼叫最近):tree.find('description-topic / access-info / index-term-set / index-term / primary /中的文件“ ajktest18.py”,第15行').text ='12345'
AttributeError:“ NoneType”對象沒有屬性“ text”
我希望能夠搜索和修改整個文件中的所有出現的內容,但是我不知道如何找到要搜索的文本的某個特定出現的位置。
這是我嘗試用來查找路徑的代碼:
import xml.etree.ElementTree as ET
tree = ET.parse('Atemplate.xml')
root = tree.getroot()
print(root.tag, root.attrib, root.text)
for child in root:
print(child.tag, child.attrib, child.text)
for label in root.iter('label'):
print(label.tag, label.attrib, label.text)
for title in root.iter('title'):
print(title.attrib)
我還嘗試了以下代碼:
with open('Atemplate2.xml') as f:
tree = ET.parse(f)
root = tree.getroot()
for elem in root.getiterator():
try:
elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED')
elem.text = elem.text.replace('FEATURE NUMBER', '12345')
except AttributeError:
pass
tree.write('output.xml')
但這會產生以下錯誤:
File "<pyshell#40>", line 2, in <module>
tree = ET.parse(f)
File "C:\MyPath\Python35-32\lib\xml\etree\ElementTree.py", line 1182, in parse
tree.parse(source, parser)
File "C:\ MyPath \Python35-32\lib\xml\etree\ElementTree.py", line 594, in parse
self._root = parser._parse_whole(source)
File "C:\ MyPath \Python35-32\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError:“ charmap”編解碼器無法解碼位置1119中的字節0x9d:字符映射到
##最終更新-這是最后對我有用的代碼(謝謝你,賈拉德!):
import lxml.etree as ET #using lxml instead of xml preserved the comments #adding the encoding when the file is opened and written is needed to avoid a charmap error with open('filename.xml', encoding="utf8") as f: tree = ET.parse(f) root = tree.getroot() for elem in root.getiterator(): try: elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED') elem.text = elem.text.replace('FEATURE NUMBER', '123456') except AttributeError: pass #tree.write('output.xml', encoding="utf8") # Adding the xml_declaration and method helped keep the header info at the top of the file. tree.write('output.xml', xml_declaration=True, method='xml', encoding="utf8")
注意事項:
xml.etree.ElementTree
庫 這是對這個出色答案的修改。 關鍵是,您需要讀取XML文件並進行解析。
import xml.etree.ElementTree as ET
with open('xmlfile.xml', encoding='latin-1') as f:
tree = ET.parse(f)
root = tree.getroot()
for elem in root.getiterator():
try:
elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED')
elem.text = elem.text.replace('FEATURE NUMBER', '123456')
except AttributeError:
pass
tree.write('output.xml', encoding='latin-1')
請注意,您可以將encoding
參數更改為其他參數,例如: utf-8
, cp1252
, ISO-8859-1
等。確實取決於您的系統和文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.