Python 选择一个文件并从中读取单词
我需要这方面的帮助,我完全是python的初学者。我的任务是创建一个程序,让用户选择一个类别,然后对该类别中的文件中的单词进行置乱。我只是想弄清楚为什么第一部分不起作用,第一部分是根据用户选择的类别运行的四种不同方法中的第一种Python 选择一个文件并从中读取单词,python,Python,我需要这方面的帮助,我完全是python的初学者。我的任务是创建一个程序,让用户选择一个类别,然后对该类别中的文件中的单词进行置乱。我只是想弄清楚为什么第一部分不起作用,第一部分是根据用户选择的类别运行的四种不同方法中的第一种 print ("Instructions: Enter your chosen category, animals, places, names or colors.") viewYourFile = input("Enter your category") categ
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-5个字母。 请阅读(文档)[关于读取函数的工作原理。括号中的数字是您要读取的字节数 您可能需要一个更简单的解决方案,例如读取整个文件并将其拆分为单词。这类似于:
file_contents = animals.read()
animalList = file_contents.split()
如果split对您来说是新的,那么(查找)[该方法也是新的
下一个问题是,您已将动物列表设置为文字字符串,而不是您读取的输入值。我想您希望该行读取:
animalList = [animal1, animal2, animal3, animal4, animal5]
你的缩进到处都是;请修复它。这样更好吗?不是真的。这段代码仍然无法运行。对不起,这是怎么回事?什么是“第一部分”,它应该做什么,它在做什么?