gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
我有一个txt里面有很多行,每一行是一个短语如红色的安全帽,现在还有一个文件夹里面有很多txt,我希望统计所有txt中上面txt短语出现的次数,并且按照次数进行排序,python…
- User
我有一个txt里面有很多行,每一行是一个短语如红色的安全帽,现在还有一个文件夹里面有很多txt,我希望统计所有txt中上面txt短语出现的次数,并且按照次数进行排序,python实现 最好加一个配置 比如txt中前100个字中出现短语的次数
- Assistant
可以通过 Python 实现对多个文本文件中短语出现次数的统计,并根据出现次数进行排序。下面是一个简单的示例代码,完成了你所要求的功能。
import os from collections import defaultdict def read_keywords(file_path): """读取包含短语的txt文件,返回一个短语列表""" with open(file_path, 'r', encoding='utf-8') as f: keywords = [line.strip() for line in f if line.strip()] return keywords def count_keywords_in_files(keywords, folder_path, char_limit=100): """统计每个短语在所有txt文件中出现的次数""" counts = defaultdict(int) for filename in os.listdir(folder_path): if filename.endswith('.txt'): file_path = os.path.join(folder_path, filename) with open(file_path, 'r', encoding='utf-8') as f: content = f.read()[:char_limit] # 只读取前 char_limit 个字符 for keyword in keywords: counts[keyword] += content.count(keyword) return counts def main(keywords_file, folder_path, char_limit=100): keywords = read_keywords(keywords_file) counts = count_keywords_in_files(keywords, folder_path, char_limit) # 按照出现次数排序 sorted_counts = sorted(counts.items(), key=lambda x: x[1], reverse=True) # 打印结果 for keyword, count in sorted_counts: print(f"{keyword}: {count}") if __name__ == "__main__": keywords_file = 'keywords.txt' # 短语文件名 folder_path = 'your_txt_folder' # 存放txt文件的文件夹路径 char_limit = 100 # 统计的字符限制 main(keywords_file, folder_path, char_limit)