【问题标题】:Python re match only letters from wordPython仅重新匹配单词中的字母
【发布时间】:2017-06-27 13:13:51
【问题描述】:

我是 Python re 的新手,但我需要帮助。我在这里搜索,谷歌,文档,但没有任何效果。所以这就是我想要做的。

我有单词(例如)“字符串” 然后我有单词列表:

字符串、字符串、str、ing、in、ins、rs、重音

我想匹配如下:string、str、ing、in、ins、rs。

我不想匹配:重音,字符串(因为有2x,而word字符串中只有1个)

  • 仅匹配单词 string 中的字母。

抱歉英语不好,如果我解释得不够好。

是的,而且有些字母是 unicode。

【问题讨论】:

    标签: python regex python-2.x


    【解决方案1】:

    我不认为你可以用正则表达式做到这一点,但我认为你可以用collections做到这一点:

    >>> from collections import Counter
    >>> target = "string"
    >>> words = ["strings", "string", "str", "ing", "in", "ins", "rs", "stress"]
    >>> [word for word in words if not Counter(word) - Counter(target)]
    ['string', 'str', 'ing', 'in', 'ins', 'rs']
    

    【讨论】:

    • 对不起,我没有提到 - 我正在使用大量的单词.....所以这种方法需要很长时间。使用 re 我在 7 秒内完成(但我找不到我正在搜索的功能)。 编辑: 我可以将它们结合起来得到结果。非常感谢。
    • @MakaloneLOgman - 我以为你说你无法使用正则表达式。
    • 真是一个很好的例子。
    • 我认为你可以通过预计算来加快速度Counter(target)
    【解决方案2】:

    本着问题的精神,这是一个正则表达式的答案。

    Here's the regex 一起玩。

    我是^(?=[string]{1,6}$)(?!.*(.).*\1).*$

    这会检查 string 中出现 1-6 次字符。 后半部分确保没有重复。 当然,如果您的原始 sstring 中有多个相同的字符,这种方法就会失效,而且它对于长字符串并不是特别有效。

    为通用输入词运行它的代码:

    import re
    mylist = ["strings", "string", "str", "ing", "in", "ins", "rs", "stress"]
    word = "string"
    r = re.compile("^(?=[%s]{1,%d}$)(?!.*(.).*\1).*$" % (word, len(word)))
    print filter(r.match, mylist)
    

    打印出来:

    ['string', 'str', 'ing', 'in', 'ins', 'rs']

    您可以使用代码here

    【讨论】:

      【解决方案3】:

      正则表达式可能不是最好的解决方案。这是一种算法:

      • 为您的目标词制作一个字典,其中每个字母是一个键,值是该字母在单词中的数量。例如对于 strings 的键:值对将是 {'s':1}
      • 对于您要测试的每个单词,检查字典中的每个字母是否都在并且字母数不超过目标单词中的数。

      【讨论】:

        【解决方案4】:

        我认为你完全不需要使用 Python re。如果我理解你的话,你只想得到字母不能重复的单词。

        这个问题可以用下面两行 Python 代码来解决。

        str_list = [u'strings', u'string', u'str', u'ing', u'in', u'ins', u'rs', u'stress']
        new_list = [i for i in str_list if len(set(i)) == len(i) ]
        print new_list
        

        程序的输出是:

        [u'string', u'str', u'ing', u'in', u'ins', u'rs']
        

        对于 unicode 字符串,您必须使用 unicode 字符串类或代码页。您不能使用 utf-8 表示。 函数 set 从可迭代对象创建 unique 集。可迭代对象也是字符串。重复的字母被删除。如果您删除某些内容,则长度不能与原始字符串相同。

        【讨论】:

          猜你喜欢
          • 2015-08-22
          • 1970-01-01
          • 2018-08-30
          • 2012-02-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-25
          • 2013-08-25
          相关资源
          最近更新 更多