2017-08-07 82 views
2

我试图利用列表理解从一个非常大的文件进行排序数据。文件结构如下:跳过列表comprehnsion 2行

THING 
info1 
info2 
info3 
THING 
info1 
info2 
info3 

...等等。

基本上试图将所有info1收集到列表中,并将所有info2收集到另一个列表中。我有一个前面的脚本来做这件事,但速度很慢。我也试图使它面向对象,所以我可以更有效地使用数据。

旧脚本:

info1_data = [] 
info2_data = [] 
with open(myfile) as f: 
    for line in f: 
     if re.search('THING',line): 
      line=next(f) 
      info1_data.append(line) 
      line=next(f) 
      info2_data.append(line) 

新的脚本:

def __init__(self, file): 
    self.file = file 

def sort_info1(self): 
    with self.file as f: 
     info1_data = [next(f) for line in f if re.search('THING',line)] 
    return info1_data 

def sort_info2(self): 
    with self.file as f: 
     info2_data = [next(f).next(f) for line in f if re.search('THING',line)] 
    return info2_data 

新的脚本适用于越来越info1_data为列表。但是,要获得info2_data,我找不到任何用这种方法跳过2行的东西。我猜对了next(f).next(f)。它运行但不产生任何东西。

这可能吗?

非常感谢。

从摩西的帮助我有这个解决方案。 islice虽然很令人困惑,但我并没有完全理解它,即使在阅读python.docs之后。 iterable是否获取数据(即info1或info2)或者执行start,stop和step来指定提取哪些数据?

islice(迭代器,启动,停止[,步])

from itertools import islice 
import re 

class SomeClass(object): 
    def __init__(self, file): 
     self.file = file 

    def search(self, word, i): 
     self.file.seek(0) # seek to start of file 
     for line in self.file: 
      if re.search(word, line) and i == 0: 
       line = next(self.file) 
       yield line 
      elif re.search(word, line) and i == 1: 
       line = next(self.file) 
       line = next(self.file) 
       yield line 

    def sort_info1(self): 
     return list(islice(self.search('THING',0), 0, None, 2)) 

    def sort_info2(self): 
     return list(islice(self.search('THING',1), 2, None, 2)) 


info1 = SomeClass(open("test.dat")).sort_info1() 
info2 = SomeClass(open("test.dat")).sort_info2() 
+1

写给你自己的'next'函数,该函数将跳过的行数作为第二个参数,缺省值为1. –

回答

2

你应该seek文件回到起点,以重复从文件的开始搜索。此外,您可以使用生成器函数将搜索操作与数据生成分离。然后使用itertools.islice迈过线:

from itertools import islice 

class SomeClass(object): 
    def __init__(self, file): 
     self.file = file 

    def search(self, word): 
     self.file.seek(0) # seek to start of file 
     for line in self.file: 
      if re.search(word, line): 
       # yield next two lines 
       yield next(self.file) 
       yield next(self.file) 

    def sort_info1(self): 
     return list(islice(self.search('THING'), 0, None, 2)) 

    def sort_info2(self): 
     return list(islice(self.search('THING'), 1, None, 2)) 

但是代替传递文件的,我会建议你通过文件路径,而不是这样的文件可能是每次使用后关闭,避免举起当他们不是(或尚未)需要时的资源。

+0

谢谢!我是新来的islice ...我已经将它加入到我的脚本中,但它只是返回搜索词'THING'作为列表而不是info1或info2作为列表。我已经浏览了python文档,但仍然不太遵循它。 – matman9

+0

@ matman9你是否从发电机功能中产生正确的项目? –

+0

在生成器中应该'....,0,None,2'返回info1?谢谢 – matman9

1

你可以这样做:

def sort_info2(self): 
    with self.file as f: 
     info2_data = [(next(f),next(f))[1] for line in f if re.search('THING',line)] 
    return info2_data 

但它看起来有点怪异的方式!