试图打印文件中的随机行,但它一次打印一个字符

2024-04-25 02:13:21 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能就是这么简单。我正在编写脚本从文件中打印随机行,但它一次打印一个字符。这是密码。你知道吗

from twython import Twython, TwythonError
import random, time

filename = open('test.txt')
line = random.choice(filename.readlines())
filename.close()

for line in line:
print line

任何帮助都是非常感谢的。我是一个初学者,所以说实话,这可能是一些简单的事情。你知道吗


Tags: fromtestimporttxt脚本密码timeline
3条回答

有几件事,首先是可读性:

for line in line
    print line #which line do you mean?

现在

line = random.choice(filename.readlines())

只会在文件中给你一个随机的行,它不会给你一个随机顺序的所有行。你知道吗

您可以通过一个简单的调用来洗牌数组

import random

filename = open('new_file.txt')

lines = filename.readlines()

random.shuffle(lines)

for line in lines:
    print line

你也可以一直从数组中随机抽取物品,直到它为空

import random

filename = open('new_file.txt')

lines = set( filename.readlines() )

while( len(lines) != 0 ):
    choice = random.choice(list(lines))
    print(choice)
    lines.remove(choice)

这个答案可能有用:randomly selecting from array

random.choice一次只返回元素,必须改用shuffle

from twython import Twython, TwythonError
import random, time

filename = open('test.txt')
lines = filename.readlines()
filename.close()

random.shuffle(lines)

for line in lines:
    print line

这里的问题是random.choice将返回一个字符串。实际上,你是在一个字符串上迭代。您应该做的是在调用random.choice之后调用split(),这样您就得到了一个单词列表而不是一个字符串。然后您的迭代将按预期工作。你知道吗

另外,您确实不应该这样迭代:

for line in line

更改迭代器:

for word in line

另外,在处理文件时习惯使用context managers也是一种很好的做法。e、 g.:

with open(some_file) as f:
    # do file actions here

所以,您的最终解决方案如下所示:

import random

with open('new_file.txt') as f:
    line = random.choice(f.readlines()).split()

for word in line:
    print(word)

相关问题 更多 >