Python:统计一个txt文件中单词出现的频率

Python: count frequency of words in a txt file

我需要计算文本文件中关键词的出现频率。我不允许使用字典或集,我也不能导入任何 Python 方法。老实说,我不知道该怎么做!!

它应该是这样显示的:

car 4
dog 4
egg 3

这是我目前所拥有的,但绝对行不通。

fname = input("enter file name:")
ifile = open(fname, 'r')
list1 = ['car', 'dog', 'cat'.....'ect']
list2 = []

for word in ifile:
    if word in list1:
        list2.index(word)[1] += 1
    else:
        list2.append([word,])

打印(list2,)

鉴于您不能使用任何 set/list 结构,为什么不使用另一个字符串并写下遇到的唯一单词,并在存在时递增。伪代码:

  • 创建用于存储的空字符串
  • 解析和提取单词
  • 迭代
  • 根据字符串检查单词(如果存在:递增/如果不存在:添加并将计数设置为 1)
  • 输出字符串

我试了一下...我注意到出于某种原因我必须在引号中输入文件名。

fname = input('enter file name:')
ifile = open(fname, 'r')
list1 = []
list2 = []

for line in ifile.readlines():
    for word in line.split(' '):
        word = word.strip()
        if word in list1:
            list2[list1.index(word)] += 1
        else:
            list1.append(word)
            list2.append(1)


for item in list1:
    print item, list2[list1.index(item)]