【问题标题】:Which sentence has more common words with the given list of words在给定的单词列表中,哪个句子有更多常用词
【发布时间】:2021-05-18 08:30:34
【问题描述】:

我有一个常用词和几个句子的列表。

我需要检查哪个句子有更多常用词。

我有一个函数可以计算给定句子中常用词的总数,我可以用它来比较不同句子的计数:

def get_words_count_in_sentence(text, words_list):
    cnt = 0
    for word in words:
        cnt += text.lower().count(word.lower())
    return cnt

但问题是我还需要考虑句子包含的列表中有多少不同词。

例如:如果第一个句子包含 10 次列表的第一个单词,第二个句子包含 1 次列表的第一个单词,2 次第二个单词,1 次第三个单词,那么第二个句子应该被认为更相似。

如何更新我的代码以实现此优先级?

【问题讨论】:

    标签: python string algorithm


    【解决方案1】:

    你可以让你的函数返回一个元组,其中第一个数字是不同单词的数量,第二个是你已经计算出来的。这样,当两个短语使用相同数量的不同单词(匹配)时,第二个数字将打破平局:

    def get_words_count_in_sentence(text, words):
        total = 0
        distinct = 0
        text = text.lower()
        for word in words:
            freq = text.count(word)
            if freq > 0:
                distinct += 1
                total += freq
        return distinct, total
    
    
    words = ["bad", "ugly", "dirty", "horrible"]
    
    i = get_words_count_in_sentence("What a bad, bad day. So bad, it makes me feel bad.", words)
    j = get_words_count_in_sentence("What a bad day. The weather is horrible and the windows are dirty.", words)
    
    print(i)  # (1, 4)
    print(j)  # (3, 3)
    print(j > i)  # True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2023-04-06
      • 2020-05-23
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多