如何在没有尾随换行符的情况下打印?

我正在尝试创建一个程序,该程序接受输入,然后将其从澳大利亚原住民语言转换为英语。虽然程序的其余部分正常运行,但输出以错误的格式打印。我收到的输出是:


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: ")

以下是字典的内容.txt:


afternoon,wuraji-wuraji

I,ngaju

bird,jirripirdi

like,kuja-piya

dance,juka-pinyi

python,malilyi

laugh,ngarlarrimi

we,ngalipa


天涯尽头无女友
浏览 75回答 2
2回答

人到中年有点甜

我会说这是文件中的换行字符,你保留在变量中,例如值,所以当你打印它时,会做一个新行,添加一个操作来删除前导空格/换行字符aboriginalngaju\n\nrstrip()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()

慕斯709654

我添加了 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python