"查找txt文件中的字符,从下一行返回一个字符"

2024-04-25 01:04:02 发布

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

好的,我有这个文本文件结构

Customer ID: 1
Customer Name: John
Customer Sale: 5

假设我希望使用customer id在文本文件中搜索这个条目,并返回customer sale:5的内容

我有类似的东西

with open("sales.txt", "r") as salesFile:
        lines = salesFile.readlines()
        for line in lines:
            if (str(ID)) in line:
                return ????

不知道如何返回一个值,从我搜索的值向下两行

提前谢谢


Tags: nameinidline条目customersalejohn
3条回答

你想要下两行,这是比赛后的下两行

with open("a.txt") as sales:
    lines=sales.readlines()

    for i in range(len(lines)-1):
        if ("ID: "+str(5)) in lines[i]:
            print lines[i+1],lines[i+2]

输出:

Customer Name: John
Customer Sale: 5

通过使用枚举器:

with open("a.txt") as sales:
    lines=sales.readlines() 
         for i,a in enumerate(lines):
             if ("ID: "+str(5)) in a:
                 print lines[i+2]

输出:

Customer Sale: 5

在这里你可以找到两种解决方法,第二种是更具脓性的。这两个函数都将Customer ID作为参数,第二个是客户ID行和要返回的所需行之间的偏移量,最后一个是输入文件。如果id不存在,函数返回None。 如果不需要将偏移量传递给函数,可以删除它并在函数内部声明

def get_id_details(c_id,offset,in_file):
    base_line = 'Customer ID: %s' % c_id
    find = False
    with open(in_file) as f:
        for line in f:
            if (base_line == line.rstrip('\r\n') and not find ):
                find = True
            if (find):
                offset -=1
            if offset ==-1:
                return line
    return None  

def get_id_details_2(c_id,offset,in_file):
    base_line = 'Customer ID: %s' % c_id
    with open(in_file) as f:
        for line in f:
            if (base_line == line.rstrip('\r\n')):
                try:
                    for _ in range(offset-1):
                        f.next()
                    return f.next()
                except StopIteration:
                    return None
print get_id_details(2,2,'in.txt')
// result is Customer Sale: 5
print get_id_details(8,6,'in.txt')
// result is None

print get_id_details_2(2,2,'in.txt')
// result is Customer Sale: 6
print get_id_details_2(5,2,'in.txt')
// result is None

输入文件

Customer ID: 1
Customer Name: John1
Customer Sale: 5
Customer ID: 2
Customer Name: John2
Customer Sale: 6
Customer ID: 4
Customer Name: John3
Customer Sale: 7
Customer ID: 3

不需要拆分行,则文件将是一个迭代器: 你可以这样做:

def match_line(ID, f):
    with open(f) as file:
        for line in file:
            if str(ID) in line:
                for line2 in file:
                    if 'Sale' in line2:
                        return line2

使用文件调用时:

In [9]: match_line(1, 'sales.txt')
Out[9]: 'Customer Sale: 5\n'

这是假设您想要在其上带有字符串'Sale'的行,如果您想要其后的两行:

def match_line(ID, f):
    with open(f) as file:
        for line in file:
            if str(ID) in line:
               next(file)
               return next(file)

相关问题 更多 >