[英]select specific lines with specific condition from a large text file with python
[英]How to select a line randomly with a specific condition in Python from a text file
我可以征求意见吗? 我需要 select 带有条件的文本文件中的特定行。 所以我试着用这个:
import random
def pick_random_resto(restaurant_obj_list):
content = open ('resto_input.txt','r')
random_restaurant = content.readlines()
print("Restaurant: " + random.choice(random_restaurant))
它确实有效,但条件是从尚未访问的餐厅中随机选择 select。 这是文本文件的内容(N:未访问,Y:已访问):
"Kanto Freestyle Breakfast", "Y"
"The Giving Cafe", "N"
"el Chupacabra", "Y"
"Ebi 10", "N"
"Jumong", "Y"
所以我想知道是否可以使用“w”创建一个新的文本文件,其中复制尚未访问的餐厅并删除访问过的餐厅。 或者有比这更好的方法吗? 对不起,我是新手。
有几种方法可以 go 执行此操作,这取决于 function 将如何运行以及在什么上下文中运行。 如果您只是想运行一个脚本来读取文件,抓取一家尚未访问过的餐厅,然后更新文件,我建议您执行以下操作。
def get_unvisited_restaurant():
with open('resto_input.txt', 'r') as f:
restaurants = f.readlines()
unvisited = [r for r in restaurants if '"N"' in r]
if len(unvisited) == 0:
print('No more new restaurants')
return
random_unvisited = random.choice(unvisited)
print("How about we try", random_unvisited)
idx = restaurants.index(random_unvisited)
restaurants[idx] = random_unvisited.replace('"N"', '"Y"')
with open('resto_input.txt', 'w') as f:
f.writelines(restaurants)
因此,首先我们从文件中读取文本,使用with
which 将在完成后自动关闭文件,这是从文件中读取的 Python 方式。 然后我们使用列表解析过滤餐厅,在该行中查找“N”(带有双引号的大写 N)。 然后我们检查我们有没有去过的餐馆,如果没有,我们打印一条友好的消息并返回,否则, random.choice
会抛出一个错误。 如果我们有未光顾的餐馆, random.choice
将 select 之一。 然后我们从完整列表中获取餐厅的索引,以便我们可以更新条目,最后使用with open
、 w
和writelines
将其写回我们的文件。
使这更容易前进的另一种方法是将您的餐馆存储在字典中并将其保存为 JSON 文件。 它是人类可读的,并且在 python 中也很容易解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.