【问题标题】:Python matching strings within substrings子字符串中的 Python 匹配字符串
【发布时间】:2021-08-25 02:05:41
【问题描述】:

我正在编写一个程序来获取一个 json 格式的文件并创建一个代理 PAC 文件。我遇到的挑战之一是 json 文件包含组织不整齐的混合数据。我想这样总结数据:

输入数据:

www.example.com
*.example.com
example.com
myserver.example.com
server.*.example2.com
server.mydomain1.example2.com
server.mydomain2.example2.com
server.mydomain3.example2.com
example2.com

输出数据:

*.example.com
example.com
server.*.example2.com
example2.com

我正在尝试找到最 Python 的方式来汇总数据。有任何想法吗?我曾想过使用正则表达式来帮助进行模式匹配,但我想它们会很快变得复杂吗?

【问题讨论】:

    标签: python string design-patterns wildcard matching


    【解决方案1】:

    我只能想出一个非常混乱的方法来做到这一点,但我会尝试用 cmets 来解释。

    import re
    l = ["www.example.com",
         "*.example.com",
         "example.com",
         "myserver.example.com",
         "server.*.example2.com",
         "server.mydomain1.example2.com",
         "server.mydomain2.example2.com",
         "server.mydomain3.example2.com",
         "example2.com"]
    # Something can only summarize if it contains a wildcard. Otherwise it won't represent the other elements in the list
    summarizable = [domain for domain in l if "*" in domain] 
    [url for url in l 
        if not bool( # check to see if url is not represented by any of the wildcards
            [1 for summary in summarizable # escape the ., replace * with re wildcard (.*)
                if bool(re.match(summary.replace('.','\.').replace('*','.*'), url)) ])] + summarizable
    

    返回

    ['example.com', 'example2.com', '*.example.com', 'server.*.example2.com']
    

    此解决方案的注意事项:如果您有两个可以相互汇总的通配符 url,它们都将出现在最终输出中。

    【讨论】:

    • 哇!这是解决问题的创造性方法!谢谢!我也非常感谢您指出您的代码可以做什么的警告,因为我可能不会明白这一点!
    • 谢谢,如果这回答了您的问题,您可以将其标记为已接受?
    • 抱歉,这里还是个新手。不知道在哪里接受答案!
    • 不用担心,我们非常感谢您的努力!
    猜你喜欢
    • 2019-06-26
    • 1970-01-01
    • 2020-05-26
    • 2023-03-28
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 2013-06-22
    • 2016-03-08
    相关资源
    最近更新 更多