如何识别文本文件唯一词汇并按用户输入批量替换所有对应词
嘿,我来帮你搞定这个问题!核心思路就是先抓出文本里实际存在的目标唯一词汇,逐个收集你的替换需求,最后批量完成替换。我给你写个完整的Python实现,每一步都给你讲明白:
完整可运行代码
def replace_words_in_file(file_path): # 1. 安全读取目标文件内容 try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() except FileNotFoundError: print(f"出错啦:文件 {file_path} 找不到!") return # 2. 定义你要替换的词汇范围(可以根据需求随时修改这个集合) target_words = {'dog', 'cat', 'bird'} # 3. 从文本里筛选出实际出现的、不重复的目标词汇 # 这里用正则提取纯单词,避免标点干扰(比如dog.、cat,这类情况) import re words_in_content = re.findall(r'\b\w+\b', content) # 筛选出在目标列表里的词,再去重 unique_targets = list(set(word for word in words_in_content if word in target_words)) if not unique_targets: print("文本里没找到需要替换的词汇哦!") return # 4. 逐个询问替换目标 replace_map = {} print("\n请输入以下词汇的替换内容:") for word in unique_targets: replacement = input(f"把 '{word}' 换成:").strip() # 允许留空跳过该词汇的替换 if replacement: replace_map[word] = replacement # 5. 执行全局替换(精确匹配独立单词,不会误伤类似doggy这种词) modified_content = content for original, new_word in replace_map.items(): modified_content = re.sub(rf'\b{original}\b', new_word, modified_content) # 6. 保存结果,给用户选择覆盖原文件或存新文件 save_choice = input("\n替换完成!要覆盖原文件吗?(输入y覆盖,其他则保存为新文件):").strip().lower() if save_choice == 'y': with open(file_path, 'w', encoding='utf-8') as f: f.write(modified_content) print(f"已成功覆盖原文件 {file_path}") else: new_file = f"{file_path}_modified.txt" with open(new_file, 'w', encoding='utf-8') as f: f.write(modified_content) print(f"替换后的内容已保存到 {new_file}") # 替换成你的文本文件路径就行 replace_words_in_file("your_text_file.txt")
关键逻辑拆解
- 精准提取单词:用正则
\b\w+\b抓取纯单词,避免标点和单词连在一起的情况(比如dog.)被漏判。 - 去重处理:用
set()自动去重,不会让你重复输入同一个词的替换内容。 - 精确替换:同样用正则
\b确保只替换独立的目标单词,不会把doggy里的dog也换掉。 - 灵活保存:给你选择覆盖原文件还是存新文件,避免误操作丢失原内容。
如果需要调整目标词汇,直接修改target_words集合就行,比如加个fish或者删掉bird都很方便~
内容的提问来源于stack exchange,提问作者Ankur
相关产品推荐
相关产品推荐

