如何计算特定行后2行的所有行中的单词?

时间:2016-08-05 14:41:41

标签: python

所以,这听起来有点令人困惑,我会试着解释一下。例如,从这些行:

next line 1
^^^^^^^^^^^^^^^^^^
red blue dark ten lemon
next line 2
^^^^^^^^^^^^^^^^^^^
hat 45 no dad fate orange
next line 3
^^^^^^^^^^^^^^^^^^^
tan rat lovely lemon eat 
you him lemon Daniel her"

我只对“柠檬”的数量感兴趣,这些“绿色”来自上面两行的“下一行”。所以,我期望的输出是“2柠檬”。

任何帮助将不胜感激!

到目前为止,我的尝试是:

#!/usr/bin/env python
#import the numpy library
 import numpy as np

  lemon = 0

  logfile = open('file','r')

  for line in logfile:

  words = line.split()

  words = np.array(words)
  if np.any(words == 'next line'):
    if np.any(words == 'lemon'):
        lemon +=1
print "Total number of lemons is %d" % (lemon)

但只有当它与“下一行”位于同一行时才会计算“柠檬”。

2 个答案:

答案 0 :(得分:3)

对于每一行,您需要能够访问它之前的两行。为此目的,您可以使用itertools.tee创建两个独立的文件对象(类似于迭代器的对象),然后使用itertools.izip()来创建您期望的对:

from itertools import tee, izip
with open('file') as logfile:
    spam, logfile = tee(logfile)
    # consume first two line of spam
    next(spam)
    next(spam)
    for pre, line in izip(logfile, spam):
        if 'next line' in pre:
             print line.count('lemon')

或者,如果您只想计算行数,可以在sum()中使用生成器表达式:

from itertools import tee, izip
with open('file') as logfile:
    spam, logfile = tee(logfile)
    # consume first two lines of spam
    next(spam)
    next(spam)
    print sum(line.count('lemon') for pre, line in izip(logfile, spam) if 'next line' in pre)

答案 1 :(得分:1)

你可以循环遍历文件(这是一个迭代器)并在找到next行时调用next line两次,然后count lemon出现for的频率,next循环和with open("data.txt") as f: lemon_count = 0 for line in f: if "next line" in line: next(f) # skip next line lemon_count += next(f).count("lemon") # get count for next-next line 调用都使用相同的迭代器。

lemon_count

对于您的示例,2最终为next。这假设在next行和lemon行之间没有其他lemon行,或者next行本身是func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reviewCellID, forIndexPath: indexPath) as! ReviewCell if let comment = selectedCompany.reviews?[indexPath.row].comment { cell.commentLabel.text = comment } return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if let comment = selectedCompany.reviews?[indexPath.row].comment { let height:CGFloat = estimateFrameForText(comment).height return CGSizeMake(collectionView.frame.width - 12, height + 70) } } func estimateFrameForText(text: String) -> CGRect { let size = CGSize(width: collectionView.frame.width - 36, height: 1000) let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin) return NSString(string: text).boundingRectWithSize(size, options: options, attributes: [NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 12.0)!], context: nil) }