我是Python的新手(我通过CodeAcademy课程学习了它)并且可以使用一些帮助来搞清楚这一点.
我有一个文件’TestingDeleteLines.txt’,大约有300行文字.现在,我试图让它从该文件中打印出10条随机行,然后删除这些行.
所以,如果我的文件有10行:
Carrot
Banana
Strawberry
Canteloupe
Blueberry
Snacks
Apple
Raspberry
Papaya
Watermelon
我需要它从这些行中随机挑出,告诉我它是随机挑选的蓝莓,胡萝卜,西瓜和香蕉,然后删除这些行.
问题是,当Python读取文件时,它会读取该文件,一旦它到达结尾,它就不会返回并删除这些行.我目前的想法是,我可以将行写入列表,然后重新打开文件,将列表与文本文件匹配,如果找到匹配项,则删除行.
我目前的问题是双重的:
>它复制了随机元素.如果它选择一条线,我需要它不再选择相同的线.但是,使用random.sample似乎不起作用,因为当我稍后使用每一行附加到URL时,我需要将这些行分开.
>我不觉得我的逻辑(写入数组 – >在文本文件中找到匹配 – >删除)是最理想的逻辑.有没有更好的方法来写这个?
import webbrowser
import random
"""url= 'http://www.google.com'
webbrowser.open_new_tab(url+myline)""" Eventually, I need a base URL + my 10 random lines opening in each new tab
def ShowMeTheRandoms():
x=1
DeleteList= []
lines=open('TestingDeleteLines.txt').read().splitlines()
for x in range(0,10):
myline=random.choice(lines)
print(myline) """debugging, remove later"""
DeleteList.append(myline)
x=x+1
print DeleteList """debugging, remove later"""
ShowMeTheRandoms()
解决方法:
I have a file, ‘TestingDeleteLines.txt’, that’s about 300 lines of text. Right now, I’m trying to get it to print me 10 random lines from that file, then delete those lines.
#!/usr/bin/env python
import random
k = 10
filename = 'TestingDeleteLines.txt'
with open(filename) as file:
lines = file.read().splitlines()
if len(lines) > k:
random_lines = random.sample(lines, k)
print("\n".join(random_lines)) # print random lines
with open(filename, 'w') as output_file:
output_file.writelines(line + "\n"
for line in lines if line not in random_lines)
elif lines: # file is too small
print("\n".join(lines)) # print all lines
with open(filename, 'wb', 0): # empty the file
pass
如果需要,它是O(n ** 2)算法can be improved(对于像输入这样的小文件,你不需要它)
标签:python,algorithm,random
来源: https://codeday.me/bug/20190923/1814113.html