重新排序和替换xml文件中文本的windows脚本?

2024-06-06 15:08:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现了几个类似的问题,但没有一个完全达到我的目标,我想编辑一个xml文件中的多行。我的脚本知识充其量是非常基本的,所以请包括一些细节,我的基本大脑将了解

我正在努力改变这个

    <?xml version="1.0" encoding="UTF-8"?>
  <channels>
    <channel update="i" site="openwebif" site_id="1:0:1:D32E:836:2:11A0000:0:0:0:" xmltv_id="&amp;TV">&amp;TV</channel>
    <channel update="i" site="openwebif" site_id="1:0:1:2F17:7EF:2:11A0000:0:0:0:" xmltv_id="4Music">4Music</channel>
    <channel update="i" site="openwebif" site_id="1:0:1:5302:814:2:11A0000:0:0:0:" xmltv_id="4seven">4seven</channel>

在这里

    <?xml version="1.0" encoding="UTF-8"?>
  <channels>
<!-- vermin --><channel id="&amp;TV">1:0:1:D32E:836:2:11A0000:0:0:0:</channel><!-- VM -->
<!-- vermin --><channel id="4Music">1:0:1:2F17:7EF:2:11A0000:0:0:0:</channel><!-- VM -->
<!-- vermin --><channel id="4seven">1:0:1:5302:814:2:11A0000:0:0:0:</channel><!-- VM -->

我甚至不知道什么最有效?这可以用python实现吗?批量?你知道吗

短暂性脑缺血发作


Tags: idversionchannelsitevmupdatexmltv
1条回答
网友
1楼 · 发布于 2024-06-06 15:08:05
import re

# Open the xml file.
with open('test1.xml', encoding='utf-8') as r:

    # Read the file contents whole.
    content = r.read()

    # Do replacements using regex.
    content = re.sub(r'^\s*(<channel)\s+.*?\s+site_id="(.*?)"\s+xmltv_id="(.*?)">.*?(</channel>)',
                     r'<!  vermin  >\1 id="\3">\2\4<!  VM  >', content, 0, re.I + re.M)

    # Open and write the changed xml file.
    with open('test2.xml', 'w', encoding='utf-8') as w:
        w.write(content)

使用python3是因为您在问题摘要中提到Python。你知道吗

这是使用正则表达式来修改XML。 如果XML有一个合理的常量结构,就像上面的例子一样, 这样就可以达到你的目标了。你知道吗

test1.xml被读取,修改是使用 具有re.sub()的正则表达式模式。你知道吗

test2.xml是应用了更改的XML文件。你知道吗

这两个文件都被视为utf-8。你知道吗

阅读关于^{}模块的Python帮助文件。你知道吗

所用正则表达式的简要概述。你知道吗

  • ^匹配行首。你知道吗
  • \s匹配空白字符。你知道吗
  • *匹配0个或多个上一个模式|字符。你知道吗
  • +匹配一个或多个上一个模式|字符。你知道吗
  • (.*?)将任何字符捕获为一个不贪婪的组。你知道吗
  • \1是作为替代物的第一组。\2是第二组。。。你知道吗
  • re.I是不敏感标志。你知道吗
  • re.M是多行标志,因此可以使用线锚^$。你知道吗

建议您阅读Python帮助文件,因为它比 全面学习。你知道吗

相关问题 更多 >