基于给定代码生成数字文件number.txt 读出numbres.txt中所有的数据
查找出出现次数最多的50个数,并将这些数写入文件top50.txt
写不出文件,不知道哪里出了问题,麻烦给看下。
with open("D:\\number.txt","r",encoding="utf-8") as file:
nums = file.readlines()
dict_temp={}
for num in nums:
dict_temp[num]=nums.count(num)
with open("D:\\top50.txt","w",encoding="utf-8") as file:
a = sorted(dict_temp.items(), key=lambda x: x[1], reverse=True)[:50]
for temp in a:
file.write(temp)
主要是变量域的问题
dict_temp={}
with open("D:\\number.txt","r",encoding="utf-8") as file:
nums = file.readlines()
for num in nums:
dict_temp[num]=nums.count(num)
with open("D:\\top50.txt","w",encoding="utf-8") as file:
a = sorted(dict_temp.items(), key=lambda x: x[1], reverse=True)[:50]
for temp in a:
file.write(temp)