【问题标题】:How can I count a word from all lines that are 2 rows after a specific line?如何从特定行之后 2 行的所有行中计算一个单词?
【发布时间】:2016-08-08 19:47:50
【问题描述】:

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

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)

但只有当它与“下一行”在同一行时才算“柠檬”。

【问题讨论】:

  • 在您的示例中,搜索条件根本不匹配。 'next' 后面永远不会跟着 'lemon' 下面两行。
  • 是的。 1号线-下1号线,2号线-^^^^^^^^,3号线-红蓝暗十柠檬等
  • 啊,好的。您发布的文本在每行之间添加了换行符。

标签: python


【解决方案1】:

对于每一行,您需要能够访问它之前的两行。为此,您可以使用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)

【讨论】:

  • 嗨 Kasramvd,如果我需要做相反的事情(计算某行上方的两行,而不是下方),我是否只需在您的代码中交换“下一行”和“柠檬”?
  • @EmilyT。根据什么样的条件计算某行上方的两行?如果没有条件,只需计算留置权并乘以 2。
  • 所以基本上,当你看到“下一行”时,数一下上面两行中的柠檬这个词。
  • @EmilyT。你想数lemon这个词或有那个词的行吗?这也是您从原始问题中想要的吗?
  • 我想数柠檬这个词,是的,但我没有在我现在意识到的原文中指定它
【解决方案2】:

您可以遍历文件(这是一个迭代器)并在找到next line 行时调用next 两次,然后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 行和lemon 行之间没有其他next 行,或者lemon 行本身就是next 行。

【讨论】:

  • 嗨 tobias,我可以对上面的 2 行而不是下面的行做同样的事情吗?
  • @EmilyT。上面两个更难,因为你不能在迭代器中倒退。您可以使用我的方法并颠倒条件,即检查lemon是否在该行中,前进两行,然后检查这是否是“下一行”行,但是如果有柠檬三个和两个,这可能会错过柠檬“下一行”上方的行。在这种情况下,@Kasramvd 方法会更好。
猜你喜欢
  • 2018-06-06
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
相关资源
最近更新 更多