如何从搜索文件中获取后续行?

时间:2016-03-29 22:08:31

标签: python

我有一个文本文件。我想在这个文件中搜索某个单词,然后返回紧接的后续行。

在我的测试用例中,我有许多颜色数值,前面是颜色名称。我希望能够输入颜色名称并获取数值。这是我的代码:

def colorF(c):
    h = 0
    r = False
    try:
        f = open("Colors.txt")
        t = list(f.read().split())
        for line in t:
            h += 1
            if str(c) in line:
                u = line
                print(u)
                go = False
                start = '('
                end = ')'

                with open("Colors.txt") as infile:
                    for l in infile:
                        g = l.strip()
                        if start in g and str(c) in line: go = True
                        elif end in g:
                            go = False
                            continue
                        if go: return (g)
    finally:
        f.close()

我可以得到一些帮助吗?我不确定我做错了什么。

3 个答案:

答案 0 :(得分:1)

您的代码似乎过于复杂。首先,通过只读取一次文件,一次一行,并且如果在给定行中找到颜色名称,仅返回next line来简化:

def colorF(colorName):
    with open("Colors.txt") as colorFile:
        for line in colorFile:
            if str(colorName) in line:
                try:
                    return next(colorFile)
                except StopIteration:
                    raise Exception("File is malformed: no value existed after color found.")  # There is probably a more specific iteration that works here
        return Exception("Color not found")  # There is probably a more appropriate exception to return here

你的代码有很多其他的错误:它不清楚你正在尝试用它做什么,但根据你的描述似乎没必要。

如果找不到颜色或文件找到颜色但没有后续值,则会Exception加注。这可以通过多种方式处理,但是建议您在这种情况下引发异常,以便调用代码知道它无法从文件中获取值。

答案 1 :(得分:1)

我对你使用拆分后文件格式的理解是这样的:

Blue 12
Red 34
Green 56

而不是这样:

Blue
12
Red
34

如果是这种情况我会用:

def colorF(c):
with open("Colors.txt", "r") as file:
    for line in file:
        words = line.split()
        for word in words:
            if word in c:
                try:
                    ret = next(word)
                    return int(ret)
                except ColorError:
                    raise Exception("The specified color was not in the file.")
                    return None

答案 2 :(得分:0)

我真的不明白你的病情是什么......但这可能就是答案

for line in f:
    if some_condition(line):
        return next(f) # return the next line
相关问题