我有 XML 檔案,我需要將欄位名稱更改為全大寫字母。我正在嘗試在 Python 中自動執行此操作,并且只能將檔案的整行轉換為全部大寫。
有沒有辦法只將文本大寫:
<Index Name="NAME">Name to Capitalize</Index>
在 Python 中看起來像這樣?:
<Index Name="NAME">NAME TO CAPITALIZE</Index>
有人告訴我嘗試使用 python 來自動執行此操作。目前我們使用批處理腳本或手動更改文本。這就是我到目前為止所擁有的。
import re
file_input = 'index.XML'
file_output = 'output.XML'
with open(file_input) as file_object:
for line in file_object:
# replace the effected line with all caps
if re.search('<Index Name="NAME">', line):
line = line.upper().rstrip()
line = line.rstrip()
print(line)
# write each line to a file
file_output = open("output.XML", 'a')
file_output.write(line '\n')
uj5u.com熱心網友回復:
對于有問題的代碼,可以進行如下更改以獲得所需的結果。或者也可以使用xmltree -
import re
f=open(r'input.xml', "r")
f_out = open("output.XML", 'a')
newtag=''
while(True):
line = f.readline()
if not line:
break
if re.search('<Index Name="NAME">', line):
newtag = line [:line.find('>') 1] line[line.find('>') 1:line.find('</')].upper() line[line.find('</'):]
print (newtag, end="") ## Not needed for this code
else:
newtag = line
f_out.write(newtag)
將產生結果 -
$ more input.xml
<Index Name="NAME">name to capitalize</Index>
<Index Name="NAME">name to capitalize</Index>
<Index Name="IDX1">name to capitalize</Index>
<Index Name="NAME">name to capitalize</Index>
<Index Name="IDX2">name to capitalize</Index>
$ python replace_in_file.py
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="NAME">NAME TO CAPITALIZE</Index>
$ more output.XML
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="IDX1">name to capitalize</Index>
<Index Name="NAME">NAME TO CAPITALIZE</Index>
<Index Name="IDX2">name to capitalize</Index>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474969.html
標籤:python-3.x xml 文本 代替
