我有一个字符串和一个定义如下的列表
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。你知道吗
关于第1部分,我认为这应该是可行的,我建议使用regex而不是字符串。拆分寻找语言。你呢也可以使用nltk.word\u标记化如果你的句子有复杂的单词和标点符号。他们都比我慢字符串。拆分但是如果你需要它们,它们是有用的。你知道吗
这里有几个不错的帖子强调了这些区别(wordpunct tokenize基本上是一个伪装的regex):
nltk wordpunct_tokenize vs word_tokenize
Python re.split() vs nltk word_tokenize and sent_tokenize
结果
对于第2部分来说,这样的方法应该是可行的,尽管它不是一个超级干净的解决方案。如果您不希望它们按顺序排列,而是彼此相邻,请检查索引是否相距1。你知道吗
结果:
使用
True
是1,False
是0的固有编码。 对in
结果的值求和:对于给定的输入,它打印
we happy
。你知道吗关于:
mamun
的观点,我们还想确保整个单词匹配。您需要拆分my_list
中的每个字符串以获得可用单词的列表。kaya3
已经发布了我想让你做的事情。你知道吗两个字符串之间的公共词可以使用集合交集进行计算。结果集的
len
给出了字符串共有的字数。你知道吗首先使用集合并集构建
my_list
中字符串中所有单词的集合:然后检查交叉点是否有长度
>= 3
:相关问题 更多 >
编程相关推荐