根据短语在 Python 中的出现来整理短语的程序
假设,我们有两个列表;包含一些选定短语的“短语”和包含多个句子的“句子”,这些句子可能包含或不包含其他列表中的短语。我们必须找出第一个列表中的各种短语是否出现在第二个列表中,并根据它们在第二个列表中的出现对第一个列表短语进行排序。我们返回排序列表“短语”作为输出。
所以,如果输入像短语=['强','耐用','高效'],句子=['产品耐用高效','坚固耐用','它高效','喜欢它因为它是高效的'],那么输出将是['高效','耐用','强']
短语“高效”出现在句子0、2和4中。它出现次数最多,因此位于输出的开头。短语“durable”和“strong”分别出现在句子0、1和1中。因此,这些短语获得输出中的下一个位置。
示例
让我们看看以下实现以获得更好的理解-
def solve(phrases, sentences): cnt = {} for feature in phrases: cnt[feature] = 0 for response in sentences: p = response.split() s = set(p) for i in s: if i in cnt: cnt[i] += 1 res = [[k, cnt[k]] for k in cnt] res.sort(key = lambda x:(-x[1], phrases.index(x[0]))) return [i[0] for i in res] print(solve(['strong', 'durable', 'efficient'], ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient']))
输入
['strong', 'durable', 'efficient'], ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient']输出结果
['efficient', 'durable', 'strong']