批量统计文件夹内所有txt内英文单词的个数的python代码
时间:2023-11-07 10:59:16作者:技术经验网浏览:459
可以使用Python的glob和re模块统计一个文件夹内所有.txt文件中英文单词的个数。以下是一个示例代码,它会遍历指定文件夹内的所有.txt文件,并统计每个文件中英文单词的数量,再将结果保存到一个名为jieguo.txt的文件中,txt内的保存格式为:txt标题---字数。
import glob import re import os def count_words_in_files(directory): # 使用glob模块找到所有的.txt文件 files = glob.glob(f'{directory}/*.txt') # 创建一个字典来存储每个文件的单词计数 word_counts = {} # 遍历所有文件 for file_path in files: # 打开文件进行读取 with open(file_path, 'r', encoding='utf-8') as file: text = file.read() # 使用正则表达式找到所有的单词 words = re.findall(r'b[A-Za-z]+b', text) # 获取文件名 file_name = os.path.basename(file_path) # 计算单词数量并将其与文件名相关联 word_counts[file_name] = len(words) return word_counts def save_results_to_file(word_counts, output_file): # 将计数结果保存到文件 with open(output_file, 'w', encoding='utf-8') as f: for file_name, count in word_counts.items(): f.write(f"{file_name}---{count} ") # 使用示例 directory_path = 'path/to/your/directory' # 替换为你的文件夹路径 word_counts = count_words_in_files(directory_path) # 结果保存到 jieguo.txt output_file_path = 'path/to/your/directory/jieguo.txt' # 替换为结果文件的路径 save_results_to_file(word_counts, output_file_path) print(f"Results have been saved to {output_file_path}")
此代码将统计结果保存到每行格式为txt文件名---字数的指定的输出文件中。注意:确保替换directory_path和output_file_path为你的实际文件夹和结果文件路径。
再实际的应用过程中会出现一篇文章中有中文和英文的情况,如果只统计中文字数(忽略英文单词),那么可以使用以下代码:
如果你想要统计中文文本中的汉字数量,可以使用Python的re模块。以下是一个修改过的版本,它会统计中文汉字的数量而忽略英文单词:
import glob import re import os def count_chinese_characters_in_files(directory): # 使用glob模块找到所有的.txt文件 files = glob.glob(f'{directory}/*.txt') # 创建一个字典来存储每个文件的汉字计数 character_counts = {} # 遍历所有文件 for file_path in files: # 打开文件进行读取 with open(file_path, 'r', encoding='utf-8') as file: text = file.read() # 使用正则表达式找到所有的中文字符 chinese_characters = re.findall(r'[\u4e00-\u9fff]', text) # 获取文件名 file_name = os.path.basename(file_path) # 计算汉字数量并将其与文件名相关联 character_counts[file_name] = len(chinese_characters) return character_counts def save_results_to_file(character_counts, output_file): # 将计数结果保存到文件 with open(output_file, 'w', encoding='utf-8') as f: for file_name, count in character_counts.items(): f.write(f"{file_name}---{count} ") # 使用示例 directory_path = 'path/to/your/directory' # 替换为你的文件夹路径 character_counts = count_chinese_characters_in_files(directory_path) # 结果保存到 jieguo.txt output_file_path = 'path/to/your/directory/jieguo.txt' # 替换为结果文件的路径 save_results_to_file(character_counts, output_file_path) print(f"Results have been saved to {output_file_path}")
在上面的代码中,re.findall这行是关键,它会匹配所有的中文汉字。请确保将directory_path和output_file_path替换为你自己的路径。