【问题标题】:Python 3 dictionary.get() function not working with sys.stdinPython 3 dictionary.get() 函数不适用于 sys.stdin
【发布时间】: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


【解决方案1】:

尾随 '\n' 是问题所在。 string = string.rstrip('\n') 为我解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 2017-05-25
    • 1970-01-01
    相关资源
    最近更新 更多