我想在python中使用文本文件中的單詞而不是直接寫入python文件中的單詞(在這種情況下,代碼完美地工作)製作混雜遊戲。但是,當我想導入他們,我得到這個列表:在Python中使用讀取文本文件創建一個使用字符串的列表
[['amazement', ' awe', ' bombshell', ' curiosity', ' incredulity', '\r\n'], ['godsend', ' marvel', ' portent', ' prodigy', ' revelation', '\r\n'], ['stupefaction', ' unforeseen', ' wonder', ' shock', ' rarity', '\r\n'], ['miracle', ' abruptness', ' astonishment\r\n']]
我想的話在一個單一的列表進行排序,例如:
["amazement", "awe", "bombshell"...]
這是我的Python代碼:
import random
#Welcome the player
print("""
Welcome to Word Jumble.
Unscramble the letters to make a word.
""")
filename = "words/amazement_words.txt"
lst = []
with open(filename) as afile:
for i in afile:
i=i.split(",")
lst.append(i)
print(lst)
word = random.choice(lst)
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: ")
#congratulate the player
if(guess==theWord):
print("Congratulations! You guessed it")
else:
print ("Sorry, wrong guess.")
input("Thanks for playing. Press the enter key to exit.")
我有文字的文本文件:
amazement, awe, bombshell, curiosity, incredulity,
godsend, marvel, portent, prodigy, revelation,
stupefaction, unforeseen, wonder, shock, rarity,
miracle, abruptness, astonishment
謝謝你的幫助和任何建議!
一行程序的伎倆!感謝您的詳細解答和解答。 –