Python字符串匹配-在另一个列表中的句子中,查找列表中的特定单词数量是否存在

2024-10-05 14:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串和一个定义如下的列表

my_string = 'she said he replied'
my_list = ['This is a cool sentence', 'This is another sentence','she said hello he replied goodbye', 'she replied', 'Some more sentences in here', 'et cetera et cetera...']

我试图检查my_string中的任何字符串中是否至少存在3个单词。我采用的方法是分割my_string,并使用all进行匹配。但是,只有当my_string中的所有项都存在于my_list中的一个句子中时,这种方法才有效

if all(word in item for item in my_list for word in my_string.split()):
    print('we happy')

1-如果句子列表中至少有3个my_string项,如何使条件得到满足?你知道吗

2-是否可以只按相同的顺序匹配my_string中的第一个和最后一个单词?i、 e“she”和“repled”出现在my_list索引3的“she repled”中,返回True。你知道吗


Tags: 字符串in列表stringismythissentence
3条回答

关于第1部分,我认为这应该是可行的,我建议使用regex而不是字符串。拆分寻找语言。你呢也可以使用nltk.word\u标记化如果你的句子有复杂的单词和标点符号。他们都比我慢字符串。拆分但是如果你需要它们,它们是有用的。你知道吗

这里有几个不错的帖子强调了这些区别(wordpunct tokenize基本上是一个伪装的regex):

nltk wordpunct_tokenize vs word_tokenize

Python re.split() vs nltk word_tokenize and sent_tokenize

import re

num_matches = 3

def get_words(input):
    return re.compile('\w+').findall(input)

my_string = 'she said he replied'
my_list = ['This is a cool sentence', 'This is another sentence','she said hello he replied goodbye', 'she replied', 'Some more sentences in here', 'et cetera et cetera...']

my_string_word_set = set(get_words(my_string))
my_list_words_set = [set(get_words(x)) for x in my_list]

result = [len(my_string_word_set.intersection(x)) >= num_matches for x in my_list_words_set]
print(result)

结果

[False, False, True, False, False, False]

对于第2部分来说,这样的方法应该是可行的,尽管它不是一个超级干净的解决方案。如果您不希望它们按顺序排列,而是彼此相邻,请检查索引是否相距1。你知道吗

words = get_words(my_string)
first_and_last = [words[0], words[-1]]
my_list_dicts = []
for sentence in my_list:
    word_dict = {}
    sentence_words = get_words(sentence)
    for i, word in enumerate(sentence_words):
        word_dict[word] = i
    my_list_dicts.append(word_dict)

result2 = []
for word_dict in my_list_dicts:
    if all(k in word_dict for k in first_and_last) and word_dict[first_and_last[0]] < word_dict[first_and_last[1]]:
        result2.append(True)
    else:
        result2.append(False)

print(result2)

结果:

[False, False, True, True, False, False]

使用True是1,False是0的固有编码。 对in结果的值求和:

if sum(word in item for item in my_list for word in my_string.split()) >= 3:
    print('we happy')

对于给定的输入,它打印we happy。你知道吗

关于:mamun的观点,我们还想确保整个单词匹配。您需要拆分my_list中的每个字符串以获得可用单词的列表。kaya3已经发布了我想让你做的事情。你知道吗

两个字符串之间的公共词可以使用集合交集进行计算。结果集的len给出了字符串共有的字数。你知道吗

首先使用集合并集构建my_list中字符串中所有单词的集合:

all_words = set.union(*[set(item.split()) for item in my_list])

然后检查交叉点是否有长度>= 3

search_words = set(my_string.split())
if len(search_words & all_words) >= 3:
    print('we happy')

相关问题 更多 >