我正在尝试创建一个需要输入的程序,然后将其从澳大利亚土著语言转换为英语。当程序的其余部分正常工作时,输出将以错误的格式打印。我收到的输出是:
ngaju
kuja-piya
malilyi
我想收到的是:
ngaju kuja-piya malilyi
这是我的完整代码:
dictionary = open('dictionary.txt')
words = {}
for line in dictionary:
english, aboriginal = line.split(',')
words[english] = aboriginal
translator = input("English: ")
while translator:
sentence = translator.split()
for word in sentence:
print(words[word], end='')
translator = input("English: ")
这是dictionary.txt的内容:
afternoon,wuraji-wuraji
I,ngaju
bird,jirripirdi
like,kuja-piya
dance,juka-pinyi
python,malilyi
laugh,ngarlarrimi
we,ngalipa
答案 0 :(得分:3)
我会说这是文件中的换行符,您将其保留在aboriginal
变量中,该变量将例如为值ngaju\n
,因此在打印时,\n
会使新行,添加rstrip()
操作以删除前导空格/换行符
for line in dictionary:
english, aboriginal = line.rstrip().split(',')
words[english] = aboriginal
最安全的方法是,在两个词上都应用.strip()
,以确保仅接收需要的内容,但如果文件格式正确(没有空格),则可能会造成一些过大的打击
for line in dictionary:
english, aboriginal = line.split(',')
words[english.strip()] = aboriginal.strip()
答案 1 :(得分:2)
我添加了strip()来删除每个单词的尾部空格,如下所示:
dictionary = open('dictionary.txt')
words = {}
for line in dictionary:
english, aboriginal = line.split(',')
words[english] = aboriginal.strip()
translator = input("English: ")
while translator:
sentence = translator.split()
print(' '.join(words[word] for word in sentence))
translator = input("English: ")
输入
I like python
输出
ngaju kuja-piya malilyi