如何使用Python查找所有输入字符串中的单词?

时间:2014-01-21 11:54:31

标签: python text keyword words

在python中,无论如何比较两个不同的文本行来查看两个或多个单词是否匹配?

非常感谢

2 个答案:

答案 0 :(得分:4)

您可以使用集合并计算交集:

>>> a = "one two three"
>>> b = "one three four"
>>> set(a.split()) & set(b.split())
set(['three', 'one'])
>>> 

答案 1 :(得分:0)

您可以拆分每一行以获取存在的单词列表。然后比较列表以检查常用词。

def get_common_words_count(str1, str2):
    list1 = str1.split()
    list2 = str2.split()
    c = 0
    for word in list1:
        try:
            list2.index(word)
            c += 1
        except ValueError:
            pass
    return c

print get_common_words_count('this is the first', 'and this is the second')
相关问题