【问题标题】:Count the number of times a word is repeated in a text file计算一个单词在文本文件中重复的次数
【发布时间】:2022-12-12 05:05:20
【问题描述】:

我需要编写一个程序,提示输入文本文件的名称,并打印具有最大和最小频率的单词,以及它们的频率(以空格分隔)。

这是我的文字

I am Sam
Sam I am
That Sam-I-am
That Sam-I-am
I do not like
that Sam-I-am
Do you like
green eggs and ham
I do not like them
Sam-I-am
I do not like
green eggs and ham

代码:

file = open(fname,'r')
dict1 = []
for line in file:
  line = line.lower()
  x = line.split(' ')
  if x in dict1:
    dict1[x] += 1 
  else:
    dict1[x] = 1 

然后我想遍历键和值并找出哪个是最大频率和最小频率但是到目前为止我的控制台说

类型错误:列表索引必须是整数或切片,而不是列表

我也不知道那是什么意思。

对于这个问题,预期的结果是:

Max frequency: i 5
Min frequency: you 1

【问题讨论】:

  • line.split(' ') 返回一个列表,意思是x 是一个列表。另请注意,dict1 实际上也不是 dict。尝试打印出您的变量作为调试的一种方式。在这个站点上也有数百个关于这个任务的问题,已经有很多很好的答案。
  • 抱歉,dict1 应该是 dict1 = {}
  • 我见过类似的问题,但我找不到任何适用于最大和最小频率的问题

标签: python-3.x list loops text-files


【解决方案1】:

您正在使用列表而不是字典来存储词频。您不能像这样使用列表来存储键值对,您需要改用字典。以下是如何修改代码以使用字典来存储词频:

file = open(fname,'r')
word_frequencies = {} # use a dictionary to store the word frequencies

for line in file:
    line = line.lower()
    words = line.split(' ')
    for word in words:
        if word in word_frequencies:
            word_frequencies[word] += 1
        else:
            word_frequencies[word] = 1

然后迭代键并找到最小和最大频率

# iterate over the keys and values in the word_frequencies dictionary
# and find the word with the max and min frequency
max_word = None
min_word = None
max_frequency = 0
min_frequency = float('inf')

for word, frequency in word_frequencies.items():
    if frequency > max_frequency:
        max_word = word
        max_frequency = frequency
    if frequency < min_frequency:
        min_word = word
        min_frequency = frequency

打印结果

print("Max frequency:", max_word, max_frequency)
print("Min frequency:", min_word, min_frequency)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2023-04-04
    • 2011-06-20
    相关资源
    最近更新 更多