Python翻译脚本:命令行输出与提示符重叠及标点识别问题求助
Hey there! Let's fix those two annoying issues you're dealing with—they're totally solvable once you break them down.
问题1:翻译输出和命令行提示符重叠
The root cause here is simple: your loop uses print(..., end=" ") for every translated element, but never adds a final newline after the loop finishes. That's why your terminal prompt gets stuck right after the last translated word.
Quick fix: Just add a plain print() statement after your loop. This will insert a newline, pushing the terminal prompt to the next line where it belongs.
问题2:带标点的单词无法被正确识别
Right now, when you split the input by spaces, something like he, gets treated as a single key that doesn't exist in your dictionary (since you have separate entries for he and ,). We need to split each token into its "word" part and trailing punctuation first, translate the word, then append the punctuation.
The easiest way to do this is with a regular expression, which can reliably separate word characters from any trailing punctuation marks.
修改后的完整代码
import re eng_to_lang = { ".": ".", # 去掉原来的\b退格符,我们会直接把标点跟在单词后面输出 "?": "?", "!": "!", ",", ",", "he": "eh", "He": "Eh", "should": "dloulhs", "Should": "Dlouhs", "have": "evah", "Have": "Evah", "given": "nevig", "Given": "Nevig", "up": "pu", "Up": "Pu", } # UNLESS YOU KNOW WHAT YOU'RE DOING, # DO NOT TOUCH ANYTHING FROM THIS POINT ON! value = input("Enter text to translate: \n") string = value.split() for element in string: # 用正则拆分单词主体和尾随的标点 matches = re.match(r"(\w+)([.,!?]*)$", element) if matches: word = matches.group(1) punctuation = matches.group(2) # 翻译单词(找不到就保留原词),再拼接标点 translated_word = eng_to_lang.get(word, word) translated_punct = eng_to_lang.get(punctuation, punctuation) print(f"{translated_word}{translated_punct}", end=" ") else: # 处理纯标点或特殊情况,直接翻译或保留原内容 print(eng_to_lang.get(element, element), end=" ") # 最后加换行,彻底解决提示符重叠问题 print()
测试效果
If you run this modified code and input he should have given up . or He, should have given up!, you'll get clean output like this:
[joey@manjarobox Languages]$ python universal.dict Enter text to translate: he should have given up . eh dloulhs evah nevig pu . [joey@manjarobox Languages]$
No more overlapping prompt, and punctuation is now handled correctly without extra spaces!
备注:内容来源于stack exchange,提问作者user28984840




