【问题标题】:How to get frequency of words in list from a string?如何从字符串中获取列表中单词的频率?
【发布时间】:2020-08-20 17:04:30
【问题描述】:

假设我有一个单词列表和一个字符串。我想要一个新数组来表示单词列表中字符串中每个单词的频率。另外,单词的每个索引应该相同,数组的长度与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] 

【问题讨论】:

标签: python python-3.x string list


【解决方案1】:

您可以拆分句子并将其传递给Collections.counter()。有了它,您可以在单词列表中查找计数。例如:

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]

【讨论】:

  • 有没有不使用计数器的方法?我正在从 csv 文件中读取数据,它说 Counter() 不可调用
  • collections.Counter() 非常高效,是 python 标准库的一部分。它应该可用。但是,如果您想以“艰难的方式”进行操作,我已经添加了替代方法的编辑。
【解决方案2】:

由于您要求一种不使用计数器的方法,所以这里有一段代码可以工作,但不确定它的时间复杂度。

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)

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多