【问题标题】:Python searching for two words regexPython搜索两个单词正则表达式
【发布时间】:2015-03-16 06:48:56
【问题描述】:

我正在尝试查找一个句子是否包含短语“go * to”,例如“go over to”、“go up to”等。我正在使用 Textblob,我知道我可以使用下面:

search_go_to = set(["go", "to"])
go_to_blob = TextBlob(var)
matches = [str(s) for s in go_to_blob.sentences if search_go_to & set(s.words)]
print(matches)

但这也会返回诸如“去那里把这个带给他”之类的句子,这是我不想要的。任何人都知道我可以如何做类似 text.find("go * to") 的事情吗?

【问题讨论】:

    标签: python regex search nltk textblob


    【解决方案1】:

    尝试使用:

    for match in re.finditer(r"go\s+\w+\s+to", text, re.IGNORECASE):
    

    【讨论】:

      【解决方案2】:

      使用generator expressions

      >>> search_go_to = set(["go", "to"])
      >>> m = ' .*? '.join(x for x in search_go_to)
      >>> words = set(["go over to", "go up to", "foo bar"])
      >>> matches = [s for s in words if re.search(m, s)]
      >>> print(matches)
      ['go over to', 'go up to']
      

      【讨论】:

        【解决方案3】:

        试试这个

        text = "something go over to something"
        
        if re.search("go\s+?\S+?\s+?to",text):
            print "found"
        else:
            print "not found"
        

        正则表达式:-

        \s is for any space
        \S is for any non space including special characters
        +? is for no greedy approach (not required in OP's question)
        

        所以re.search("go\s+?\S+?\s+?to",text) 将匹配"something go W#$%^^$ to something" 当然这也是"something go over to something"

        【讨论】:

        • 这个答案可以做更多的解释。也许解释一下正则表达式的部分——比如单词和非单词字符类型、非贪婪问号等。
        【解决方案4】:

        这行得通吗?

        import re
        search_go_to = re.compile("^go.*to$")
        go_to_blob = TextBlob(var)
        matches = [str(s) for s in go_to_blob.sentences if search_go_to.match(str(s))]
        print(matches)
        

        正则表达式的解释:

        ^    beginning of line/string
        go   literal matching of "go"
        .*   zero or more characters of any kind
        to   literal matching of "to"
        $    end of line/string
        

        如果您不想匹配“going to”,请在to 之前和go 之后插入\\b(单词边界)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-01-25
          • 2012-03-10
          • 2011-10-13
          • 1970-01-01
          • 1970-01-01
          • 2022-12-05
          • 2013-08-16
          相关资源
          最近更新 更多