Python文本文件禁用词替换问题求助:无法替换为对应星号
Python文本替换问题:禁用词未被替换为等长星号
你的代码没生效的核心原因是错误地拿整行的单词列表去和单个禁用词匹配,根本没遍历到每个单词。具体来说:
words是个二维列表,每个元素是某一行拆分后的单词列表(比如["this", "is"])- 第二个循环里
if words[i] in banned_words是把整个行的单词列表和禁用词(单个字符串)对比,永远不可能匹配,所以替换逻辑根本没执行。
修正后的代码
# 用with语句自动管理文件,避免忘记关闭 with open('filename.txt', 'r') as f: lines = f.readlines() banned_words = {'is', 'activity', 'one'} # 用集合匹配更快 processed_lines = [] for line in lines: words = line.split() processed_words = [] for word in words: # 拆分单词和末尾的标点(比如one?拆成one和?) pure_word = '' punctuation = '' for idx, c in enumerate(word): if not c.isalnum(): pure_word = word[:idx] punctuation = word[idx:] break else: pure_word = word # 不区分大小写匹配禁用词 if pure_word.lower() in banned_words: processed_words.append('*' * len(pure_word) + punctuation) else: processed_words.append(word) # 拼接回行,保留原换行符 processed_line = ' '.join(processed_words) + '\n' processed_lines.append(processed_line) # 写入文件 with open('filename.txt', 'w') as f: f.writelines(processed_lines)
关键修正细节
- 遍历单个单词:不再对整行列表做判断,而是逐个处理每行里的每个单词
- 处理标点:针对
one?这类带标点的单词,拆分出纯单词部分匹配禁用词,替换后保留标点 - 保留原格式:不再随意
strip()和转小写,保留原文本的大小写、行内空格结构 - 更安全的文件操作:用
with语句自动关闭文件,避免资源泄漏 - 匹配优化:把禁用词改成集合,提升匹配速度(数据量大时更明显)
如果你的原输入文本是:
This is activity one?
运行修正后的代码会得到你预期的输出:
This ** ******** ***?
内容的提问来源于stack exchange,提问作者sexysmexy
相关产品推荐
相关产品推荐

