【问题标题】:How to read regular expression settings from a configuration file written in xml?如何从用 xml 编写的配置文件中读取正则表达式设置?
【发布时间】:2019-04-16 01:57:30
【问题描述】:

我的设置中有一个用 XML 编写的正则表达式。 有没有办法在 python 中将设置读取为正则表达式?

例如,有些网站的标题部分相同。 我想编写一个将这些标题视为相同的代码。

  • 标题 1:上海 - 谷歌地图
  • 标题 2:东京 - 谷歌地图


→ 将这些标题视为“Google 地图”


示例代码如下:

<config>
    <title>(.*)Google Maps</title>
</config>

如果我只是用xml.etree.ElementTree 库读取这个 xml 文件,它只是将设置读取为字符串。

提前谢谢你!

【问题讨论】:

    标签: python regex xml


    【解决方案1】:

    我假设您想从 xml 文件加载正则表达式?

    import re
    import xml.etree.ElementTree as ET
    root = ET.fromstring("<config> <title>(.*)Google Maps</title> </config>")
    conds = {c.tag: re.compile(c.text) for c in root.getchildren()}
    # example
    conds['title'].match("Tokyo - Google Maps")
    

    但我不确定我是否正确理解了您的问题。

    【讨论】:

    • 谢谢!这就是我想做的。它奏效了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多