我需要计算文本文件中关键字的频率。我不允许使用字典或集合,也不能导入任何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,])
打印(列表2)
答案 0 :(得分:0)
鉴于你不能使用任何set / list结构,为什么不使用另一个字符串并写下遇到的唯一字,在存在时递增。伪代码:
答案 1 :(得分:0)
我玩了一点......我注意到由于某种原因我必须在引号中输入文件名。
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)]