yangbaowen 发表于 2022-3-20 12:13:09

怎么统计这个文件中出现频率排前10的整数。(代码)

生成一个大文件data.txt,要求1200行,每行随即为0~20的整数。
读取data.txt文件,统计这个文件中出现频率排前10的整数。

ckblt 发表于 2022-3-20 12:38:58

# 写入

import random


with open("data.txt", "w", encoding="utf-8") as f:
    s = ""
    for i in range(1, 1201):
      s += str(random.randint(0, 20)) + "\n"
   
    f.write(s[:-1])


# 读取

d = dict([(i, 0) for i in range(0, 21)])

with open("data.txt", "r", encoding="utf-8") as f:
    n = f.read().split("\n")
    for i in n:
      d += 1

result = for i in sorted(d.items(), reverse=True, key=lambda d: d)][:10]

for i in result:
    print(i)

isdkz 发表于 2022-3-20 12:41:11

from operator import itemgetter
import random

# 生成文件
with open('data.txt', 'w') as fp:
    lst = (str(random.randint(0,20))+'\n' for _ in range(1200))
    fp.writelines(lst)

# 统计文件
with open('data.txt') as fp:
    result = {}
    for line in fp:
      temp = int(line[:-1])
      result = result.get(temp, 0) + 1
    result = dict(sorted(result.items(), key=itemgetter(1,0), reverse=True))
    for k, v in tuple(result.items())[:10]:
      print(f'随机数:{k}, 出现次数:{v}')

yangbaowen 发表于 2022-3-20 13:55:32

isdkz 发表于 2022-3-20 12:41


大佬{:5_92:}

yangbaowen 发表于 2022-3-20 14:01:01

ckblt 发表于 2022-3-20 12:38


{:10_275:}
页: [1]
查看完整版本: 怎么统计这个文件中出现频率排前10的整数。(代码)