【问题标题】:Print next x lines from string1 until string2打印从 string1 到 string2 的下 x 行
【发布时间】:2015-10-20 20:21:47
【问题描述】:

我正在尝试编写一个函数,它读取文本文件直到找到一个单词(比如“hello”),然后打印从字符串 1 开始的下 x 行字符串(比如“start_description”)直到字符串 2 (比如“end_description”)。

hello

start_description 123456 end_description

函数应该看起来像 description("hello") 并且下面的输出应该看起来像

123456

这有点难以解释。我知道如何在文本文件中找到特定的单词,但我不知道如何打印,如前所述,两个字符串(start_description 和 end_description)之间的下几行。

编辑1: 我找到了一些代码,可以打印接下来的 8、9、... 行。但是因为两个字符串之间的文本是可变长度的,所以这不起作用...

编辑2: 基本上它与这篇文章中的问题相同:Python: Print next x lines from text file when hitting string,但 range(8) 对我不起作用(参见 EDIT1)。

输入文件可能如下所示:

HELLO
salut
A: 123456.

BYE
au revoir
A: 789123.

代码应如下所示:

import re
def description(word):
    doc = open("filename.txt",'r')
    word = word.upper()

    for line in doc:
        if re.match(word,line):
            #here it should start printing all the text between start_description and end_description, for example 123456

    return output

print description("hello")
123456
print description("bye")
789123

【问题讨论】:

  • 请编辑您的帖子以包含示例输入文件和预期输出
  • 我包含了到目前为止的代码和预期的输出。
  • 请编辑您的帖子以包含您的输入文件示例和预期输出
  • 现在够精确了吗? :-)

标签: python string lines


【解决方案1】:

这是一种使用拆分的方法:

start_desc = 'hello'
end_desc = 'bye'
str = 'hello 12345\nabcd asdf\nqwer qwer  erty\n bye'

print str.split('hello')[1].split('bye')[0]

第一次拆分将导致:

('', ' 12345\nabcd asdf\nqwer qwer  erty\n bye')

因此将第二个元素提供给第二个拆分,它将导致:

('12345\nabcd asdf\nqwer qwer  erty\n ', '')

使用第一个元素。

然后,您可以根据需要使用strip() 删除周围的空格。

【讨论】:

    【解决方案2】:
    def description(infilepath, startblock, endblock, word, startdesc, enddesc):
        with open(infilepath) as infile:
            inblock = False
            name = None
            found = False
            answer = []
            for line in infile:
                if found and not inblock: return answer
                if line.strip() != startblock and not inblock: continue
                if line.strip() == startblock: inblock = True
                elif line.strip() == endblock: inblock = False
                if not line.startswith(startdesc):
                    name = line.strip()
                    continue
                if name is not None and name != word: continue
                if not line.startswith(startdesc): continue
                answer.append(line.strip().lstrip(startdesc).rstrip(enddesc))
    

    【讨论】:

    • 感谢您的代码,@inspectorG4dget,我认为这可能会有所帮助。几个小时后我会再看一遍(欧洲已经晚上 11 点了)。
    猜你喜欢
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2014-09-09
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多