【发布时间】:2025-12-23 16:10:11
【问题描述】:
我想更新我的基本混乱游戏。我已经这样做了,脚本从文本文件中获取单词,现在我想将它们分成模块,因为我有不同的文本文件和不同的单词。
我有我的主脚本,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? -
或
from amazement import *应该允许您在没有amazement前缀的情况下访问filename。 -
它工作,完美,谢谢。但稍后我也会有一个包含来自另一个文本文件的单词的 sad.py。使用
from ... import *更好吗? -
据我了解,我必须做一个输入菜单,用户可以从中选择组(模块),从中选择单词。如果我用 if 语句来做,我应该像本例那样在其中包含
import吗?def menu(): print '1. Go opA' print '2. Go opB' print '3. Exit' pick = raw_input('Pick one: ') if pick == '1': import opa opa.menu() elif pick == '2': import opb opb.menu() else: import sys sys.exit() menu()
标签: python python-3.x