【问题标题】:how to read previous and next line if the current line is valid for an IF statement in Python如果当前行对Python中的IF语句有效,如何读取上一行和下一行
【发布时间】:2013-12-08 23:25:12
【问题描述】:

我正在以这种方式读取压缩文件

import sys;
import gzip;
import csv;

def iscomment(s):            ##function to get rid of the header of the file which every line starts with #
    return s.startswith('#')

with gzip.open(sys.argv[1], 'r') as f:
    for line in dropwhile(iscomment, f):
        for line in csv.reader(f, delimiter="\t"):
            if (int(line[1]) in myHdictionary):
                print PreviousLine,"\n",line,"\n",NextLine,"\n"
            else:
                continue

因此,如果当前行满足IF语句,我想检索文件当前行的上一行和下一行。

任何建议将不胜感激! 提前致谢!

【问题讨论】:

  • 总是读 3 行,如果中间的行通过了测试,你已经有了另外两行,如果没有,读下一行。
  • 你需要在csv.reader()周围加上dropwhile();您正在做的事情发生可以工作,但是您跳过了太多行。在这种情况下,您必须跳过第一列以 # 开头的 rows
  • 为了有上一行和下一行:在内存中始终保留 两行。然后,每当这两个匹配中的最后一个匹配时,您就可以打印前两行中的第一行和当前行。

标签: python csv if-statement input


【解决方案1】:

当向后看时不要试图向前看:

from collections import deque
from itertools import islice, dropwhile
import csv

def iscomment(row): return row[0][0] == '#'

with gzip.open(sys.argv[1], 'r') as f:
    reader = dropwhile(iscomment, csv.reader(f, delimiter="\t"))
    history = deque(islice(reader, 2), maxlen=2)

    for row in reader:      
        if history[-1][1] in myHdictionary:
            print history[0]
            print history[-1]
            print row
        history.append(row)

您需要将csv.reader() 自身 包装在dropwhile() 迭代器中(带有调整的条件);否则你会在开头跳过一行csv 读者永远看不到的行。

deque 对象始终保存前 2 行,让您在浏览 CSV 文件时可以查看这些行。 history[-1] 是前一行,history[0] 是前一行。如果history[-1] 第1 列在myHdictionary 中,则您的条件匹配。

【讨论】:

  • 您好,我尝试了您的解决方案,但在“history = deque(islice(reader, 2), maxlen=2)”行中收到此错误消息 IndentationError: unindent does not match any external indentation level
  • 你在混合制表符和空格吗?确保行缩进与上一行匹配(定义reader)。
猜你喜欢
  • 2012-06-12
  • 2013-02-26
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 2018-04-22
相关资源
最近更新 更多