我想更新我的基本混雜遊戲。我已經做了,腳本從文本文件中獲取單詞,現在我想將它們分成模塊,因爲我有不同的文字文件。Python導入自己的模塊 - 名稱未定義
我有我的主腳本,jumble_game.py:
import random
import amazement
#Welcome the player
print("""
Welcome to Word Jumble.
Unscramble the letters to make a word.
""")
def wordlist(file):
with open(file) as afile:
global the_list
the_list = [word.strip(",") for line in afile for word in line.split()]
print(the_list)
def main():
score = 0
for i in range(4):
word = random.choice(the_list)
theWord = word
jumble = ""
while(len(word)>0):
position = random.randrange(len(word))
jumble+=word[position]
word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))
#Getting player's guess
guess = input("Enter your guess: ").lower()
#congratulate the player
if(guess==theWord):
print("Congratulations! You guessed it")
score +=1
else:
print ("Sorry, wrong guess.")
print("You got {} out of 10".format(score))
#filename = "words/amazement_words.txt"
wordlist(filename)
main()
我想要的文件amazement.py要導入到jumble_game.py因爲我希望用戶選擇組,從這些話會被選中。
amazement.py:
filename = "amazement_words.txt"
我得到這個錯誤:
File "jumble_game.py", line 49, in <module>
wordlist(filename)
NameError: name 'filename' is not defined
如果我做的其他方式,導入主腳本到amazement.py並運行後,代碼功能沒有問題。
任何線索我錯過了什麼?仍然是一個Python初學者對我很感興趣。 :)
感謝您的幫助/建議!
爲什麼不使用'amazement.filename'? –
或者'來自驚奇導入*'應該允許你訪問沒有'amazement'前綴的'filename'。 –
它的工作,完美,謝謝。但後來我還會用另一個文本文件中的單詞sad.py。使用'from ... import *'更好嗎? –