簡體   English   中英

Python 3 dictionary.get()函數不適用於sys.stdin

[英]Python 3 dictionary.get() function not working with sys.stdin

我目前正在編寫一個詞典程序,允許用戶輸入兩個單詞:一個英語單詞及其外來翻譯。 然后,用戶應該能夠輸入外來詞並檢索英語詞; 但是,我需要在下半年使用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()

謝謝!

尾隨的'\\ n'是問題所在。 string = string.rstrip('\\n')為我修復了此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM