python批量统计txt词频,并且输出到同一个excel中

有一个文件夹,里面全是txt文档。使用pyhton识别文件夹内所有txt文件,并且根据关键词统计出关键词词频。最终输出结果需要是一个excel文件,excel中行为自己设定的关键词,列为各个txt文件名字。最终excel是需要一个!
即统计文件夹内所有txt关键词词频,并输出到一个excel中国

需要用到pandas和xlwt模块👇

import os
import glob
import pandas as pd
import xlwt

# 设定关键词列表
keywords = ["keyword1", "keyword2", "keyword3"]

# 获取所有txt文件的文件名
txt_files = glob.glob("path/to/folder/*.txt")

# 初始化一个字典,用于存储关键词的词频
keywords_freq = {k: [0]*len(txt_files) for k in keywords}

# 循环遍历每个txt文件,计算关键词的词频
for i, txt_file in enumerate(txt_files):
    with open(txt_file, "r") as f:
        text = f.read()
        for keyword in keywords:
            keywords_freq[keyword][i] = text.count(keyword)

# 创建一个DataFrame,用于存储关键词的词频
df = pd.DataFrame(keywords_freq, index=[os.path.basename(txt_file) for txt_file in txt_files])

# 创建一个Excel文件,并将DataFrame写入到其中
book = xlwt.Workbook()
sheet1 = book.add_sheet('Sheet 1')
for i, col in enumerate(df.columns):
    sheet1.write(0, i+1, col)
for i, index in enumerate(df.index):
    sheet1.write(i+1, 0, index)
for i in range(len(df)):
    for j in range(len(df.columns)):
        sheet1.write(i+1, j+1, df.iloc[i, j])
book.save('output.xls')