Python实现拼写检查功能时如何保留输入文本的换行符?
问题原因
你当前代码丢失原有换行的核心原因是:所有输入行的单词被拆分后都存入了同一个全局列表new_list,最终仅用空格拼接所有元素,完全丢失了行与行之间的边界信息。另外你代码里还有一处变量名笔误,判断单词正确时调用的uusi_lista是未定义变量,会直接报错。
修改方案
调整处理逻辑,逐行处理输入内容,每行处理完成后单独拼接为完整行,最后用换行符拼接所有处理好的行即可保留原有格式。修改后的完整代码如下:
def main(): lahtotiedosto = open("words.txt", "r", encoding="utf-8") word_lib = [] input_list = [] for rivi in lahtotiedosto: rivi = rivi.rstrip() word_lib.append(rivi) lahtotiedosto.close() print("Enter the text to be spell-checked (empty line to end input).") typos = 0 syote = input() while syote != "": input_list.append(syote) syote = input() processed_lines = [] for line in input_list: words = line.split(" ") processed_words = [] for word in words: if word in word_lib: processed_words.append(word) else: processed_words.append(f"*{word}*") typos += 1 processed_lines.append(" ".join(processed_words)) print("Checked text, typos highlighted with '*'") ready_text = '\n'.join(processed_lines) print(ready_text) print("There were", typos, "typos.") main()
关键修改说明
- 修正了原代码的变量名笔误,避免运行报错
- 新增了
processed_lines列表单独存储每一行的处理结果,不再把所有行的单词混合存储 - 每行的单词处理完成后先拼接为当前行的完整字符串,最终用
\n拼接所有行,完全保留原始输入的换行格式 - 新增了文件关闭操作,避免资源泄露;同时把原变量名
list改为word_lib,避免和Python内置的list类型重名引发潜在问题
内容的提问来源于stack exchange,提问作者K K
相关产品推荐
相关产品推荐

