[英]How would I select a random word from a file for a user to unscramble?
I am trying to select a random word from a txt file.我正在尝试 select 来自 txt 文件的随机单词。 The context of the file has been provided.
已提供文件的上下文。 I would like the word to be random every time the code is ran.
我希望每次运行代码时这个词都是随机的。 I also only need the words before the comma
我也只需要逗号前的单词
import random
print("Please enter mywords file to start game")
user_input=input('Enter file name')
filename = open(user_input)
info=filename.readlines()
filename.close()
words=info[0-3]
objects=words.split(',')
userword=random.choice(objects)
print(userword)
opulence,great wealth
penury,extremely poor
gregarious,fond of company; sociable
entomology,study of insects
So far I able to pull from the second line in the file "penury,extremely poor"到目前为止,我可以从文件“penury,extremely Poor”的第二行中提取
You were trying to slice, but end up with just one line.你试图切片,但最后只剩下一条线。 You can do a loop over the lines, split on
','
and form a list with what's required.您可以在行上进行循环,在
','
上拆分,并形成一个包含所需内容的列表。 Later, randomly pick from the list:稍后,从列表中随机选择:
lst = []
for x in info:
w, _ = x.split(',')
lst.append(w)
print(random.choice(lst))
0-3
seems to be a typo of 0:3
, but the problem goes deeper than that. 0-3
似乎是0:3
的错字,但问题远不止于此。 words
is supposed to be a list, and lists don't have a .split
method. words
应该是一个列表,而列表没有.split
方法。 You'll need to split each item (and select the part before the comma).您需要拆分每个项目(以及 select 逗号之前的部分)。
words = [line.split(',')[0] for line in info]
userword = random.choice(words)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.