簡體   English   中英

將字典導入python腳本?

[英]Importing dictionaries into python script?

所以我正在創建一個非常基本的基於文​​本的游戲,但是我希望程序給出的答案相對正確以響應不同的輸入。 不必告訴程序為每個不同的答案寫一個特定的東西,我希望能夠將類型字典導入腳本並為不同的單詞組提供關鍵字(如否定和肯定的含義)。 這可能嗎? 我讀過的所有內容都沒有真正回答我的問題或完成我想要的...

我的模擬腳本如下:

字典包括:

a=raw_input("Are you well?")
if a=='yes':
    print("Good to hear.")
elif a=='yep":
     print("Good to hear!")  

 #I don't want to put it all in manually or use 'or'
elif a=='no':
    print("That's not good!")
elif a=='nope':
    print("That's not good!")
else:
    print("Oh.")

帶字典:

mydiction.py

NegConns=('no','nope','never','No','Nope') 
#'no' etc. is what the user inputs, NegConns is the keyword
PosConns=('yes','sure','okay','fine','good')

測試模塊

import mydiction
question=raw_input("How are you?")
if question== NegConns:
    print("That's not good.")
elif question==PosConns:
    print("Good to hear.")
else:
    print("oh.")

所以基本上如果輸入是負面的,程序是有同情心的,如果輸入是正面的,程序就會祝賀。 我不確定這是否完全符合我的要求,或者我是否以錯誤的方式解決這個問題,而且我似乎找不到幫助所以我把它放在那里......謝謝進步。

這幾乎是正確的,除非您想稍微調整一下導入語句:

from mydiction import NegConns, PosConns

並將您的相等性測試更改為數組成員資格測試,如下所示:

if question in NegConns:或者, if question in PosConns:

此外,您應該查看https://docs.python.org/3/tutorial/controlflow.html#default-argument-values 示例代碼片段看起來與您要解決的問題幾乎一模一樣。

此外,請考慮使用字典或集合而不是列表/元組。 在字典/集合上使用in運算符時,您應該獲得 O(1) 查找的好處。

我認為沒關系,但是您可以創建一個包含否定和肯定答案的列表,並在 if 語句中進行檢查。 看看它怎么運作:

    negativeAnswers = ['No','Nope','I don't think so']
    positiveAnswers = ['Yeah', 'Yes', 'Of Course']

question1 = raw_input('How are you?')

if question.lowercase() in positiveAnswers;
    print('Nice to hear that!')
elif question.lowercase() in negativeAnswers:
    print('Oh')
else:
    print('Sorry. I didn't understand you. :(')

我希望它對你有幫助。

假設您的目錄結構如下:

--\my_project    # Your directory containing the files
    -| mydiction.py
    -| testmod.py

my_project目錄中添加一個__init__.py使其成為 python模塊 現在您的項目結構將如下所示:

--\my_project   
    -| __init__.py
    -| mydiction.py
    -| testmod.py

現在為了從mydiction.py importtestmod.py ,你必須在你的testmod.py 中提到:

from mydiction import NegConns, PosConns

暫無
暫無

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

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