2016-09-13 13 views
-3

私はこれに助けが必要です、私はpythonで総初心者です。私の割り当ては、ユーザーがカテゴリを選択し、そのカテゴリにあるファイルから単語をスクランブルするようなプログラムを作成することです。この最初の部分がなぜ機能しないのかを理解したいだけです。最初の部分は、ユーザーが選択したカテゴリに応じて実行する4つの異なるメソッドのうちの最初の部分です。ファイルを選んでそれから単語を読むpython

print ("Instructions: Enter your chosen category, animals, places, names or colors.") 
viewYourFile = input("Enter your category") 

category = 'animals' 

if category == 'animals': 
    animals = open('animals.txt') 
    next = animals.read(1) 
    while next != "": 
     animal1 = animals.read(1) 
     animal2 = animals.read(2) 
     animal3 = animals.read(3) 
     animal4 = animals.read(4) 
     animal5 = animals.read(5) 
    animalList = ['animal1', 'animal2', 'animal3', 'animal4', 'animal5'] 
    chosenAnimal = random.choice(animalList) 
    animalLetters = list(chosenAnimal) 
    random.shuffle(animalLetters) 
    scrambledAnimal = ' '.join(animalLetters) 
    print(scrambledAnimal) 
    print("Enter the correct spelling of the word") 
+1

あなたのインデントはすべての場所にあります。それを修正してください。 –

+0

それは良いですか? – Naxty

+0

実際にはありません。このコードはまだ実行されません。 – Prune

答えて

2

最初の問題は、ファイルから1〜5文字だけを読み取っていることです。 どうすればの機能が動作するかについての(https://docs.python.org/2/tutorial/inputoutput.html])をお読みください。かっこ内の数字は、読みたいバイト数です。

ファイル全体を読み取って単語に分割するなどの簡単な解決策が必要な場合があります。

file_contents = animals.read() 
animalList = file_contents.split() 

場合は、同様に[https://docs.python.org/2/library/string.html]あなたに、そして(見上げる)が新しいそのメソッドを分割:これは次のようになります。

次の問題は、読み込んだ入力値ではなく、動物リストをリテラル文字列に設定したことです。私はあなたが行を読むことを望むと思う:

animalList = [animal1, animal2, animal3, animal4, animal5] 
関連する問題