批量统计匹配ID的文本词数后写入Excel失败,求排查建议
排查Excel写入失败问题的建议
我有一个包含id列的test.xlsx文件,另有一批文件名与该列ID匹配的文本文件。我希望遍历所有文件统计词数,并将结果写入Excel的word_count列。以下代码能够正确统计对应文件的词数,但无法将结果写回Excel文件,求排查建议?
文本文件名示例
1 2 3 ...
初始Excel文件结构(test.xlsx)
id word_count
期望输出
id word_count 1 3298 2 589 3 3487 4 1649 ... ...
现有代码
info = 'test.xlsx' dir = 'text' import os from pathlib import Path import pandas as pd file_word_counts = [] number_of_words = 0 for file in Path(dir).glob("**/*.txt"): with open(file, "r", encoding = 'utf-8') as f: text = f.read() word = text.split() word_count = len(word) number_of_words += word_count file_word_counts.append((file.stem, word_count)) df = pd.read_excel(info) for file_stem, word_count in file_word_counts: match = df['id'] == file_stem if match.any(): df.loc[match, 'word_count'] = word_count df.to_excel(info, index=False) print("Word count done.")
排查方向
数据类型不匹配:检查Excel中
id列的类型,如果是数字(如整数),但file.stem是字符串,两者比较会匹配失败。可以转换类型后再比较:# 把文件名转成整数匹配 match = df['id'] == int(file_stem) # 或者把Excel的id列转成字符串 match = df['id'].astype(str) == file_stem文件权限冲突:确认
test.xlsx没有被其他程序(比如Excel客户端)打开,否则Pandas无法写入被占用的文件。目标列不存在:检查Excel里是否真的有
word_count列,如果没有,代码会自动新增该列,但写入后可能因格式问题不显示。可以提前在代码里确认并创建:if 'word_count' not in df.columns: df['word_count'] = 0文件名匹配验证:在循环中打印匹配日志,确认文件名和Excel的id是否真的能对应上(比如有没有大小写、空格差异):
for file_stem, word_count in file_word_counts: match = df['id'] == file_stem print(f"尝试匹配ID: {file_stem}, 匹配结果: {match.any()}") if match.any(): df.loc[match, 'word_count'] = word_count依赖与引擎问题:确保安装了Excel写入所需的依赖包,比如
openpyxl,也可以在写入时指定引擎:pip install openpyxldf.to_excel(info, index=False, engine='openpyxl')
内容的提问来源于stack exchange,提问作者aoooooiiiiiiiiiiiiiii
相关产品推荐
相关产品推荐

