我有多个txt文本例如1.txt 如何用代码统计我需要统计每个文本中数字出现的频数,并生成excel表格形式文本形式如下:

我有多个txt文本例如1.txt 如何用代码统计
我需要统计每个文本中数字出现的频数,并保存为excel表格形式
文本形式如下:

img

需要统计每个数字出现的频数,保存为xlsx 格式如何用python写

  遍历多个*.txt文本列表,依次统计数字出现频次,将统计以*.txt为标签追加写入目标文本文件。由于我的python 环境没有成功pip pandas ,就把统计结果写入csv文本文件了。我不太看明白您是要写成一个文件不是分别统计成单独表格。先写入一个文件count.txt,后改代码为各个统计了。


  • 随机生成十个数字文本

    img


    img

  • python 代码
#!/sur/bin/nve python
# coding: utf-8
from random import choice


mypath = '/sdcard/001/num001/'

def write_numfile(filename):
    ''' 随机写入100个整数 '''
    nums = range(5001)
    
    with open(filename, 'w') as f:
        
        for i in range(100):
            f.write(f"{choice(nums)}\n") 


def main():
    
    for i in range(1, 11): # 生成10随机文本文件。
        write_numfile(f"{mypath}{i:0>3}.txt")



if __name__ == '__main__':
    main()
  • 循环遍历轮询文本文件,统计数字

    img

  • python 代码
def count_num(filename):
    ''' 统计文本中的数字 '''
    
    with open(filename) as f: # 读取文本。
        text = f.read()[:-1]

    count_dict = {} # 数字统计字典。
    for i in text.split('\n'): # 遍历轮询文本数字统计出现频次。
        count_dict[i] = count_dict.get(i, 0) + 1
    
    count = [(num, count) for num,count in count_dict.items()] # 列表解析统计字典数据。
    count.sort(reverse=True, key=lambda x: x[1])
    
    with open(f"{mypath}count.txt", 'a') as f:
        f.write(f"\n{filename}\n")
        
        for num,k in count:
            f.write(f"{num}: {k}\n")



def main():
    
    for i in range(1, 11): # 生成10随机文本文件。
        write_numfile(f"{mypath}{i:0>3}.txt")

    for i in range(1, 11): # 生成10随机文本文件。
        count_num(f"{mypath}{i:0>3}.txt")


if __name__ == '__main__':
    main()

  • 各个文档单独统计代码

    
    with open(f"{filename[:-4]}_count.txt", 'w') as f:
        f.write(f"数字,出现频次")
        
        for num,k in count:
            f.write(f"\n{num},{k}")




from collections import Counter

with open("1.txt", "r") as file:
    numbers = file.read().splitlines()

counts = Counter(numbers)

for number, count in counts.items():
    print(f"{number}:{count}次")