【问题标题】:most efficient way to go about identifying sub-strings in a string in python?在python中识别字符串中的子字符串的最有效方法?
【发布时间】:2011-01-12 19:02:35
【问题描述】:

我需要在相当长的字符串中搜索 CPV(通用采购词汇)代码。

目前我正在使用一个简单的 for 循环和 str.find() 进行此操作

问题是,如果 CPV 代码以稍微不同的格式列出,此算法将找不到它。

在字符串中搜索代码的所有不同迭代的最有效方法是什么?这仅仅是重新格式化多达 10,000 个 CPV 代码并为每个实例使用 str.find() 的情况吗?

不同格式的示例如下

30124120-1 
301241201 
30124120 - 1
30124120 1
30124120.1

等等

谢谢:)

【问题讨论】:

    标签: python string fuzzy-search


    【解决方案1】:

    试试正则表达式:

    >>> cpv = re.compile(r'([0-9]+[-\. ]?[0-9])')
    >>> print cpv.findall('foo 30124120-1 bar 21966823.1 baz')
    ['30124120-1', '21966823.1']
    

    (修改直到它与您的数据中的 CPV 紧密匹配。)

    【讨论】:

      【解决方案2】:

      尝试使用re(Python 的正则表达式)中的任何函数。请参阅the docs 了解更多信息。

      您可以制作一个正则表达式来接受这些代码的多种不同格式,然后使用re.findall 或类似的东西来提取信息。我不确定 CPV 是什么,所以我没有它的正则表达式(但也许你可以看看 Google 是否有任何正则表达式?)

      【讨论】:

        【解决方案3】:
        cpv = re.compile(r'(\d{8})(?:[ -.\t/\\]*)(\d{1}\b)')
        
        for m in re.finditer(cpv, ex):
            cpval,chk = m.groups()
            print("{0}-{1}".format(cpval,chk))
        

        应用于您的样本数据返回

        30124120-1
        30124120-1
        30124120-1
        30124120-1
        30124120-1
        

        正则表达式可以读作

        (\d{8})         # eight digits
        
        (?:             # followed by a sequence which does not get returned
          [ -.\t/\\]*   #   consisting of 0 or more
        )               #   spaces, hyphens, periods, tabs, forward- or backslashes
        
        (\d{1}\b)       # followed by one digit, ending at a word boundary
                        #   (ie whitespace or the end of the string)
        

        希望有帮助!

        【讨论】:

        • +1 用于规范化。不过,我确实建议使用r 字符串前缀而不是\\\t
        • @larsman:谢谢,我已将其更改为原始字符串并重新排序字符列表以便于理解。
        猜你喜欢
        • 1970-01-01
        • 2021-11-12
        • 2012-12-18
        • 2018-03-14
        • 2020-12-04
        • 2015-08-16
        • 2015-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多