Python中的随机选择
我需要从基于用户导入文件的列表中生成一个随机项。当我对文件使用random.choice时,程序将返回整个列表。我已经把代码贴在下面了。我需要它挑出一个我可以利用的对象Python中的随机选择,python,Python,我需要从基于用户导入文件的列表中生成一个随机项。当我对文件使用random.choice时,程序将返回整个列表。我已经把代码贴在下面了。我需要它挑出一个我可以利用的对象 import random file=input("Please enter file name: ") fhandle=open(file, 'r') wfile=fhandle.read().split('\n') words=[] words.append(wfile) random=random.choice(words
import random
file=input("Please enter file name: ")
fhandle=open(file, 'r')
wfile=fhandle.read().split('\n')
words=[]
words.append(wfile)
random=random.choice(words)
print(random)
您正在将整个列表wfile作为单个元素添加到单词列表中 您可以使用words.extendwfile将wfile的所有元素添加到words中
阅读更多关于追加和扩展的信息。我会使用类似于:
import random, os
file = input("Please enter file name: ")
if os.path.isfile(file):
with open(file) as f:
r = random.choice(list(f))
print(r)
else:
print(file, "Not found")
我会这样做:
import random
input_file=input("Please enter file name: ")
def rand_word(filename=input_file):
with open(filename) as bucket:
catch_words = [line for line in bucket]
if catch_words:
return random.choice(catch_words).rstrip('\n')
希望有帮助 您正在覆盖要导入的随机模块,不要对变量使用保留字。@尽管这是个坏主意,但它不能解释OP看到的内容。别忘了close@andreis11或者更好的是,使用with@John科尔曼,没有足够的投票机会