【发布时间】:2019-08-07 23:39:14
【问题描述】:
我目前正在编写一个字典程序,它允许用户输入两个单词:一个英文单词及其外文翻译。然后,用户应该能够输入外来词并检索英文词;但是,我需要在后半部分使用 sys.stdin。
import sys
dictionary = dict()
userInput = input()
while userInput != "":
buf = userInput.split()
english = buf[0]
foreign = buf[1]
dictionary[foreign] = english
userInput = input()
for userInput in sys.stdin:
print(type(userInput))
if userInput in dictionary:
print(dictionary.get(userInput))
else:
print("Word not in dictionary.")
当我使用 sys.stdin 时,dictionary.get() 函数无法正常运行。当我简单地使用普通的 input() 函数而不是 sys.stdin 时,字典能够正常运行。为什么会这样?如何让 sys.stdin 正确使用字典搜索?
这段代码似乎可以工作,但又一次......它使用了 input() 而不是 sys.stdin:
import sys
dictionary = dict()
userInput = input()
while userInput != "":
buf = userInput.split()
english = buf[0]
foreign = buf[1]
dictionary[foreign] = english
userInput = input()
userInput = input()
while userInput != "":
if userInput in dictionary:
print(dictionary.get(userInput))
else:
print("Word not in dictionary")
userInput = input()
谢谢!
【问题讨论】:
-
你试过
print(userInput)吗?或者更好,print(repr(userInput))?我怀疑你没有正确处理尾随空格。 -
有一个尾随
\n。 -
如何处理尾随\n?
-
text = text.rstrip('\n')删除右侧的所有\n。或者,如果您总是收到以\n结尾的文本text = text[:-1] -
请注意,如果您提供的键不在字典中,
.get方法已经允许您指定默认值。因此,对于您的情况,您可以使用print(dictionary.get(userInput, "Word not in dictionary"))而不是if ... else ...块。
标签: python dictionary get