【问题标题】:How to open a text file and traverse through multiple lines concurrently?如何打开一个文本文件并同时遍历多行?
【发布时间】:2017-04-26 15:00:21
【问题描述】:

我有一个文本文件,我想打开并根据下一行对一行执行一些操作。 例如,如果我有以下几行:

(a) A dog jump over the fire.
    (1) A fire jump over a dog.
(b) A cat jump over the fire.
(c) A horse jump over a dog.

我的代码是这样的:

with open("dog.txt") as f:
    lines = filter(None, (line.rstrip() for line in f))

for value in lines:
    if value has letter enclosed in parenthesis
        do something
    then if next line has a number enclosed in parenthesis
        do something 

编辑:这是我使用的解决方案。

for i in range(len(lines)) :
    if re.search('^\([a-z]', lines[i-1]) : 
        print lines[i-1]
    if re.search('\([0-9]', lines[i]) : 
        print lines[i]

【问题讨论】:

    标签: python file text iteration lines


    【解决方案1】:

    存储上一行,读取下一行后处理:

    file = open("file.txt")
    previous = ""
    
    for line in file:
        # Don't do anything for the first line, as there is no previous line.
        if previous != "":
            if previous[0] == "(": # Or any other type of check you want to do.
                # Process the 'line' variable here.
                pass
    
        previous = line
    
    file.close()
    

    【讨论】:

    • 不完全。我认为我需要的是两个迭代器,然后我可以将一行上的一个迭代器与另一行上的另一个迭代器进行比较。
    【解决方案2】:

    你应该使用python的iter

    with open('file.txt') as f:
        for line in f:
            prev_line = line       # current line.
            next_line = next(f)    # when call next(f), the loop will go to next line.
    
            do_something(prev_line, next_line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 2011-03-20
      相关资源
      最近更新 更多