如何从字符串中获取列表中单词的频率?

2024-04-19 13:01:40 发布

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

假设我有一个单词列表和一个字符串。我想要一个新数组,它表示单词列表中字符串中每个单词的频率。此外,单词的每个索引都应该相同,数组的长度应该与listWords相同

listWords = ['Noodles', 'Instant', 'Flavour', 'Ramen', 'Chicken', 'Flavor', 'Spicy', 'Beef'] 

string = "Cup Noodles Chicken Vegetable Noodles" 

生成的数组应如下所示:

每个索引表示列表中每个单词的频率,否则为0

result = [2, 0, 0, 0, 1, 0, 0, 0] 

Tags: 字符串列表string数组单词频率instantchicken
2条回答

您可以拆分句子并将其传递给^{}。有了它,你可以在单词列表中查找计数。例如:

from collections import Counter

string = "Cup Noodles Chicken Vegetable Noodles"
listWords = ['Noodles', 'Instant', 'Flavour', 'Ramen', 'Chicken', 'Flavor', 'Spicy', 'Beef']

counts = Counter(string.split())
[counts[word] for word in listWords]
# [2, 0, 0, 0, 1, 0, 0, 0]

不带计数器()

当然,您可以在没有Counter()的情况下执行此操作。您只需要处理第一次尝试访问密钥时发生的KeyError。然后可以使用get(word, 0)在查找单词时返回默认值0。比如:

string = "Cup Noodles Chicken Vegetable Noodles"
listWords = ['Noodles', 'Instant', 'Flavour', 'Ramen', 'Chicken', 'Flavor', 'Spicy', 'Beef']

counts = {}

for word in string.split():
    try:
        counts[word] += 1
    except KeyError:
        counts[word] = 1


[counts.get(word, 0) for word in listWords]
# still [2, 0, 0, 0, 1, 0, 0, 0]

既然您要求一种不使用计数器的方法,下面是一段可以工作的代码,但不确定其时间复杂性

listWords = ['Noodles', 'Instant', 'Flavour', 'Ramen', 'Chicken', 'Flavor', 'Spicy', 'Beef']
indicies = {}
freq = [0]*len(listWords)
for i in range(len(listWords)):
    indicies[listWords[i]] = i

string = "Cup Noodles Chicken Vegetable Noodles"

for word in string.split():
    if word in indicies.keys():
        freq[indicies[word]]+=1

print(freq)

相关问题 更多 >