2016-11-06 91 views
1

我想更新我的基本混雜遊戲。我已經做了,腳本從文本文件中獲取單詞,現在我想將它們分成模塊,因爲我有不同的文字文件。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初學者對我很感興趣。 :)

感謝您的幫助/建議!

+3

爲什麼不使用'amazement.filename'? –

+1

或者'來自驚奇導入*'應該允許你訪問沒有'amazement'前綴的'filename'。 –

+0

它的工作,完美,謝謝。但後來我還會用另一個文本文件中的單詞sad.py。使用'from ... import *'更好嗎? –

回答

3

你說過的問題是一個標準的命名空間/範圍問題。你已經在amazement.py的範圍內創建了一個變量,但是不在jumble_game.py命名空間中。因此,您無法訪問amazement.py中的頂級變量,而無需告知程序從哪裏獲取該變量。

你可以做一些事情。我將列出二:

1.

from amazement import filename

這將允許您使用「文件名」如你所描述。

或2

amazement.filename替換以filename任何參考文獻。

你可以閱讀更多關於作用域和命名空間在這裏:http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html

相關問題