![](/img/trans.png)
[英]How would I read words given by the user in a file, and replace the word with asterieks from a user given msg if the word is in the file?
[英]How would I select a random word from a file for a user to unscramble?
我正在尝试 select 来自 txt 文件的随机单词。 已提供文件的上下文。 我希望每次运行代码时这个词都是随机的。 我也只需要逗号前的单词
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
到目前为止,我可以从文件“penury,extremely Poor”的第二行中提取
你试图切片,但最后只剩下一条线。 您可以在行上进行循环,在','
上拆分,并形成一个包含所需内容的列表。 稍后,从列表中随机选择:
lst = []
for x in info:
w, _ = x.split(',')
lst.append(w)
print(random.choice(lst))
0-3
似乎是0:3
的错字,但问题远不止于此。 words
应该是一个列表,而列表没有.split
方法。 您需要拆分每个项目(以及 select 逗号之前的部分)。
words = [line.split(',')[0] for line in info]
userword = random.choice(words)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.