#统计单词出现的个数
words=[]
adict={}
#从input.txt读取数据(input.txt文件是自己创建的)
with open("input.txt","r") as f:
for line in f:
#从字符串的末尾删除空白字符以及换行符
line=line.rstrip()
#split方法返回在每个空白处拆分字符串所产生的子字符串列表
wordList=line.split()
# 将读取的数据放在列表中
for word in wordList:
word=word.rstrip(",.!?")
words.append(word)
#列表中的元素作为字典的键,元素出现的个数作为对应键的值
for i in range(len(words)):
key=words[i]
n=words.count(key)
adict[key]=n
#统计的单词数存到output.txt
with open("output.txt","w") as f1:
# 遍历字典
for key in adict:
print("%-5d %s"%(adict[key],key),file=f1)