2 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個贊
我會說這是文件中的換行字符,你保留在變量中,例如值,所以當(dāng)你打印它時(shí),會做一個新行,添加一個操作來刪除前導(dǎo)空格/換行字符aboriginalngaju\n\nrstrip()
for line in dictionary:
english, aboriginal = line.rstrip().split(',')
words[english] = aboriginal
最安全的方法,應(yīng)用于兩個單詞,以確保您只采取所需的內(nèi)容,但如果您的文件格式良好(沒有空格),則有點(diǎn)過分.strip()
for line in dictionary:
english, aboriginal = line.split(',')
words[english.strip()] = aboriginal.strip()

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個贊
我添加了 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