在随机选择lin时忽略.txt文件中的某些行

2024-04-23 15:02:05 发布

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

如何忽略文件中包含某些字符(如“Y”)的行?你知道吗

我该怎么做才能让它从文件中随机读取一行(没有“Y”的行)?你知道吗

txt文件应包含以下内容:

"Red Ribbon", "N"
"Big Bones", "Y"
"Green Dye", "Y"
"Tyrone Biggums", "N"
"Walmart-Guy-We-All-Hate", "Y"
"Trump", "N"

它应该能够随机读取其中一行与“N”每当我运行它


Tags: 文件txtgreenredall字符webig
3条回答

其他人已经贴出了答案,但这里有一个版本,这是更解包,让你更容易理解的部分。你知道吗

import random

new_line_list = []
with open("stuff.txt") as f:
    lines = [line.rstrip('\n') for line in open('stuff.txt')]
    for line in lines:
        if '\"N\"' in line:
            new_line_list.append(line)

print(random.choice(new_line_list))

有一种方法:

import random

with open("D:/sam.txt", "r") as file:
    lines = [line.rstrip() for line in file if line.rstrip().endswith(', "N"')]     #seperating those lines not containing Y

print(random.choice(lines))

您可以使用此代码段。你知道吗

import random

with open(<file_name>) as f:
    r = f.readlines()
    l = len(r)
    while True:
        c = random.randint(0, l-1)
        print(r[c].split(","))
        if r[c].split(",")[-1] != "Y":
            print(r[c])
            break

相关问题 更多 >