在XML文件中我有数百行,如以下两个示例所示:
<settings site_id="someID123" xmltv_id="Some text - dummy (2) HH">Some text - dummy (2) HH</settings>
<settings site_id="moreID321" xmltv_id="More Text">More Text</settings>
我想使用python regex格式化xmltv_id =“ HERE ”内的所有内容,且没有空格,破折号或括号,并在末尾添加 .xx
xmltv_id="Some text - dummy (2) HH"
xmltv_id="More Text"
变成这样
xmltv_id="Sometextdummy2HH.xx"
xmltv_id="MoreText.xx"
我该怎么办?
谢谢!
答案 0 :(得分:1)
请考虑以下方法-读取和解析xml,修改数据,编写xml。
import xml.etree.ElementTree as ET
tree = ET.parse('1.xml')
for element in tree.findall('settings'):
element.set('xmltv_id', element.get('xmltv_id').replace(' ', ''))
tree.write('2.xml')
原始xml 1.xml
:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<settings site_id="someID123" xmltv_id="Some text - dummy (2) HH">Some text - dummy (2) HH</settings>
</note>
修改后的xml 2.xml
:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<settings site_id="someID123" xmltv_id="Sometext-dummy(2)HH">Some text - dummy (2) HH</settings>
</note>
答案 1 :(得分:1)
在解析结构化数据(例如XML / HTML)时,Regex永远不是一种健壮且合适的方法。 使用适当的解析器。
具有etree.ElementTree
模块和re.sub
功能:
import xml.etree.ElementTree as ET
import re
root = ET.parse('yourxml.xml').getroot()
pat = re.compile(r'[\s()-]+') # regex character class for chars to replace
for el in root.findall('settings[@xmltv_id]'):
el.set("xmltv_id", pat.sub('', el.get("xmltv_id")) + '.xx')
ET.dump(root)
示例输出:
<main>
<settings site_id="someID123" xmltv_id="Sometextdummy2HH.xx">Some text - dummy (2) HH</settings>
<settings site_id="moreID321" xmltv_id="MoreText.xx">More Text</settings>
</main>
答案 2 :(得分:0)
我认为您无法使用python中的单个正则表达式来完成此操作。我能想到的解决方案是这样的:
import re
def format_line(line):
m = re.search('(.*xmltv_id=")(.*)(".*)', line)
stripped_tag = re.sub(' |-|\(|\)','', m.group(2))
return f'{m.group(1)}{stripped_tag}.xx{m.group(3)}'
>>> format_line('<settings site_id="someID123" xmltv_id="Some text - dummy (2) HH">Some text - dummy (2) HH</settings>')
'<settings site_id="someID123" xmltv_id="Sometextdummy2HH.xx">Some text - dummy (2) HH</settings>'
答案 3 :(得分:-1)
re为:
import re
xmltv_id1="Some text - dummy (2) HH"
xmltv_id2="More Text"
replace_regex = r'\s|[-]|[(]|[)]'
print(re.sub(replace_regex, '', xmltv_id1) + '.xx'))
print(re.sub(replace_regex, '', xmltv_id2) + '.xx'))