【问题标题】:Word Counting in lists列表中的字数统计
【发布时间】:2019-09-15 16:04:49
【问题描述】:

我有一个项目,其目标是计算字符串中的单词(unigrams)。解决此问题的最明显方法之一是将字符串拆分为列表,然后运行程序,以便查看是否有任何列表项相同;最后,将单词作为字典的关键字,将重复次数作为字典的关键字。我这样做了,但出现“列表索引必须是整数或切片,而不是 str”的错误消息。有什么方法可以解决这个问题(代码如下)。

words = content_string.lower()
punctuation = ["'", '"', ',', '.', '?', '!', ':', ';', '()','-']
words = "".join(i if i not in punctuation else "" for i in words)
words = words.split()

i = 0
counts = dict()

for i in words:
if words[i] in counts:
    counts[words[i]] += 1
else:
    counts[words[i]] =1

sorted_counts = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)
for i in len(range(9)):
    print(count[i])

【问题讨论】:

  • 尝试打印出i。你会发现它不是循环内的索引。想想for i in words
  • Python 在标准库中得到了Counter 对象,尝试使用他docs.python.org/3.7/library/…

标签: python python-3.x


【解决方案1】:

使用 collections.Counter (8.3 collections)

import collections
from pprint import pprint

content_string = 'I am having a project of which the goal is to count words in a string (unigrams). One of the most obvious ways to approach this is by splitting the string up to lists and then have the program run so it can see if any list items are the same; finally, put the word as the key of a dictionary, and the times of repetition as the key of the dictionary. I did this, but the error message appears of "list indices must be integers or slices, not str". What are some ways to fix this problem (code below).'

words = content_string.lower()
punctuation = ["'", '"', ',', '.', '?', '!', ':', ';', '(',')','-']
words = "".join(i if i not in punctuation else "" for i in words)
words = words.split()

word_count = collections.Counter()
for word in words:
    word_count[word] += 1

pprint(word_count.most_common())

结果

[('the', 11),
 ('of', 6),
 ('to', 4),
 ('a', 3),
 ('this', 3),
 ('i', 2),
 ('is', 2),
 ('string', 2),
 ('ways', 2),
 ('and', 2),
 ('list', 2),
 ('are', 2),
 ('as', 2),
 ('key', 2),
 ('dictionary', 2),
 ('am', 1),
 ('having', 1),
 ('project', 1),
 ('which', 1),
 ('goal', 1),
 ('count', 1),
 ('words', 1),
 ('in', 1),
 ('unigrams', 1),
 ('one', 1),
 ('most', 1),
 ('obvious', 1),
 ('approach', 1),
 ('by', 1),
 ('splitting', 1),
 ('up', 1),
 ('lists', 1),
 ('then', 1),
 ('have', 1),
 ('program', 1),
 ('run', 1),
 ('so', 1),
 ('it', 1),
 ('can', 1),
 ('see', 1),
 ('if', 1),
 ('any', 1),
 ('items', 1),
 ('same', 1),
 ('finally', 1),
 ('put', 1),
 ('word', 1),
 ('times', 1),
 ('repetition', 1),
 ('did', 1),
 ('but', 1),
 ('error', 1),
 ('message', 1),
 ('appears', 1),
 ('indices', 1),
 ('must', 1),
 ('be', 1),
 ('integers', 1),
 ('or', 1),
 ('slices', 1),
 ('not', 1),
 ('str', 1),
 ('what', 1),
 ('some', 1),
 ('fix', 1),
 ('problem', 1),
 ('code', 1),
 ('below', 1)]

PS。 for i in words: i 实际上是一个词而不是索引。如果你想要一个索引和单词,你可以这样做for i, word in enumerate(words): 但是正如你所看到的,使用 Counter 可以更短的方式解决问题。

无论如何不使用Counter你可以解决如下:

from pprint import pprint

content_string = 'I am having a project of which the goal is to count words in a string (unigrams). One of the most obvious ways to approach this is by splitting the string up to lists and then have the program run so it can see if any list items are the same; finally, put the word as the key of a dictionary, and the times of repetition as the key of the dictionary. I did this, but the error message appears of "list indices must be integers or slices, not str". What are some ways to fix this problem (code below).'

words = content_string.lower()
punctuation = ["'", '"', ',', '.', '?', '!', ':', ';', '(',')','-']
words = "".join(i if i not in punctuation else "" for i in words)
words = words.split()

word_count = {}

for word in words:
    try:
        word_count[word] += 1
    except KeyError:
        word_count[word] = 1

word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
pprint(word_count)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-15
    • 2012-02-27
    • 1970-01-01
    • 2023-01-04
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    相关资源
    最近更新 更多