[英]How to extract random words from .txt file using python?
我有一个如下所示的 .txt 文件:
Title | Author
-------------------------
title1 | author1
title2 | author2
... ...
titleN | authorN
我想从这个文件中提取 100 个随机标题,如下所示:
title1
title2
...
title100
我试过这个:
import random
with open('file.txt','r') as f:
title = f.read().split('|')
for i in range (0,100):
print(random.choice(title))
但在执行过程中,程序还会随机打印作者姓名。 我怎样才能避免这种情况?
当你这样做时:
with open(path,'r') as f:
title = f.read().split('|')
f.read()
将整个文件作为字符串提供给您。 将其拆分|
给出一个包含作者和标题(以及新行和空格)的列表.
相反,您可以像 go 一样处理行和拆分。 有类似的东西:
with open(path) as f:
titles = [l.split('|')[0].strip() for l in f]
这将为您提供一个干净的标题列表,例如:
['title1', 'title2', 'title3', 'title4', 'title5']
有了它,您可以使用random.sample()
来获取您想要的任意数量的随机项目。
import random
path = "path/to/file.txt"
n = 100
with open(path) as f:
titles = [l.split('|')[0].strip() for l in f]
random.sample(titles, n)
这假设您不想要重复项。
您可以使用.readlines()
而不是.read()
将文件逐行读取到列表中。 然后,您可以在选择随机行后使用.split('|')[0].strip()
,仅显示其中的标题部分:
import random
with open('file.txt', 'r') as f:
title = f.readlines()
for i in range(0, 100):
choice = random.choice(title)
print(choice.split('|')[0].strip())
或者,您可以在阅读文件后立即处理该文件:
import random
with open('file.txt', 'r') as f:
title = [line.split('|')[0].strip() for line in f.readlines()]
for i in range(0, 100):
print(random.choice(title))
这是.split('|')[0].strip()
工作原理的演示:
>>> choice = "title1 | author1"
>>> choice.split('|')
['title1 ', ' author1']
>>> choice.split('|')[0]
'title1 '
>>> choice.split('|')[0].strip()
'title1'
读完后看看title
。如果我的文本文件是
title1 | author1
title2 | author2
title
将为['title1 ', ' author1\ntitle2 ', ' author2\n']
。 从这个列表中随机选择有时会给你标题,有时会给你作者,有时两者兼而有之。
更好的方法如下:
import random
# read in the file and split lines
with open("file.txt", "r") as f:
lines = f.read().splitlines()
# lines = ["title1 | author1", "title2 | author2"]
titles = [line.split("|")[0].strip() for line in lines]
# titles = ["title1", "title2"]
请注意,我们需要调用strip
来去除标题末尾的任何多余空格。
您现在可以继续进行抽样,但我怀疑您需要 100 个独特的标题,而不仅仅是 100 个随机标题。 您所做的称为带替换抽样,而获得唯一标题将是不带替换抽样。 您可以按如下方式使用random.sample
完成此操作(请参阅随机文档):
print(*(random.sample(titles, 100)), sep = "\n")
或等效地使用更熟悉的语法
for samp_title in random.sample(titles, 100):
print(samp_title)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.