大型React JS项目批量词汇搜索需求:求可用工具或修复Python代码
批量搜索React项目中指定词汇的出现次数
修复后的单词汇搜索代码
原代码可能因编码异常、文件类型覆盖不全导致运行失败,以下是修复后的版本:
import os def search_text_in_directory(directory, text_to_search): total_occurrences = 0 # 扩展支持React项目常见的文件类型 target_extensions = (".js", ".jsx", ".ts", ".tsx") for root, dirs, files in os.walk(directory): # 跳过node_modules目录,避免无效搜索 if 'node_modules' in dirs: dirs.remove('node_modules') for file in files: if file.endswith(target_extensions): file_path = os.path.join(root, file) # 加入编码错误处理,防止程序中断 try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() occurrences = content.count(text_to_search) total_occurrences += occurrences if occurrences > 0: print(f"'{text_to_search}' 在 '{file_path}' 中出现 {occurrences} 次") except UnicodeDecodeError: print(f"跳过文件 {file_path}:编码格式不兼容") return total_occurrences directory_to_search = r"C:\Users\hmmer\newsapi-app" text_to_search = "news-image" total = search_text_in_directory(directory_to_search, text_to_search) print(f"'{text_to_search}' 总出现次数: {total}")
批量处理2400个词汇的方案
将所有词汇存入keywords.txt(每行一个词汇),通过脚本批量统计并导出结果:
import os import csv def search_text_in_directory(directory, text_to_search): total_occurrences = 0 target_extensions = (".js", ".jsx", ".ts", ".tsx") for root, dirs, files in os.walk(directory): if 'node_modules' in dirs: dirs.remove('node_modules') for file in files: if file.endswith(target_extensions): file_path = os.path.join(root, file) try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() total_occurrences += content.count(text_to_search) except UnicodeDecodeError: continue return total_occurrences def batch_search_keywords(directory, keywords_file, output_file): # 读取所有关键词 with open(keywords_file, 'r', encoding='utf-8') as f: keywords = [line.strip() for line in f if line.strip()] # 批量统计 results = [] for idx, keyword in enumerate(keywords, 1): count = search_text_in_directory(directory, keyword) results.append({"关键词": keyword, "出现次数": count}) print(f"[{idx}/{len(keywords)}] 完成统计: {keyword} - {count}次") # 导出结果到CSV with open(output_file, 'w', encoding='utf-8', newline='') as csvfile: fieldnames = ["关键词", "出现次数"] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(results) print(f"统计结果已保存到 {output_file}") # 配置路径 directory_to_search = r"C:\Users\hmmer\newsapi-app" keywords_file = "keywords.txt" # 你的关键词文件路径 output_file = "keyword_counts.csv" batch_search_keywords(directory_to_search, keywords_file, output_file)
使用步骤
- 将2400个词汇按每行一个的格式写入
keywords.txt - 修改
directory_to_search为你的React项目根目录 - 运行脚本,最终统计结果会保存到
keyword_counts.csv中
内容的提问来源于stack exchange,提问作者aikostr
相关产品推荐
相关产品推荐

