使用字符串以任意顺序匹配数组元素

时间:2017-04-18 09:50:42

标签: python

我是python的新手,并试图找到一条推文是否有任何查找元素。

例如。如果我能找到它应该与猫匹配的单词,那么可爱的小猫可以任意顺序匹配。但据我所知,我无法找到解决方案。任何指导表示赞赏。

import re
lookup_table = ['cats', 'cute kittens', 'dog litter park']
tweets = ['that is a cute cat',
          'kittens are cute',
          'that is a cute kitten',
          'that is a dog litter park',
          'no wonder that dog park is bad']
for tweet in tweets:
    lookup_found = None
    print re.findall(r"(?=(" + '|'.join(lookup_table) + r"))", tweet.lower())

输出

['cat']
[]
[]
['dog litter park']
[]

预期产出:

that is a cute cat > cats
kittens are cute > cute kittens
this is a cute kitten > cute kittens
that is a dog litter park > dog litter park
no wonder that dog park is bad > dog litter park

3 个答案:

答案 0 :(得分:0)

对于只有一个单词文本的查找单词,您可以使用

for word in tweet

对于像“可爱的小猫”这样的查找单词,您希望任何订单。只需将该单词拆分并在推文字符串中查找即可。

这是我尝试过的,它效率不高但是它的工作原理。尝试运行它。

lookup_table = ['cat', 'cute kitten', 'dog litter park']
tweets = ['that is a cute cat',
          'kittens are cute',
          'that is a cute kitten',
          'that is a dog litter park',
          'no wonder that dog park is bad']

for word in lookup_table:
    for tweet in tweets:
        if " " in word:
            temp = word.split(sep=" ")
        else:
            temp = [word]
        for x in temp:
            if x in tweet:
                print(tweet)
                break

答案 1 :(得分:0)

我将如何做到这一点。我认为lookup_table不需要太严格,我们可以避免复数;

import re
lookup_table = ['cat', 'cute kitten', 'dog litter park']
tweets = ['that is a cute cat',
      'kittens are cute',
      'that is a cute kitten',
      'that is a dog litter park',
      'no wonder that dog park is bad']
for data in lookup_table:
    words=data.split(" ")
    for word in words:
        result=re.findall(r'[\w\s]*' + word + '[\w\s]*',','.join(tweets))
        if len(result)>0:
            print(result)

答案 2 :(得分:0)

问题1:

单数/复数: 只是为了让事情滚动,我会使用inflect,一个python包来摆脱奇异&复数等...

问题2:

拆分和加入: 我写了一个小脚本来演示如何使用它,没有经过强大的测试,但应该让你感动

import inflect 
p = inflect.engine()
lookup_table = ['cats', 'cute kittens', 'dog litter park']
tweets = ['that is a cute cat',
          'kittens are cute',
          'that is a cute kitten',
          'that is a dog litter park',
          'no wonder that dog park is bad']

for tweet in tweets:
    matched = []
    for lt in lookup_table:
            match_result = [lt for mt in lt.split() for word in tweet.split() if p.compare(word, mt)]
            if any(match_result):
                matched.append(" ".join(match_result))
    print tweet, '>>' , matched