【问题标题】:Finding data in-between two strings in python在python中查找两个字符串之间的数据
【发布时间】:2015-02-05 13:50:47
【问题描述】:

我有一个文本文件,其中包含一些格式,例如:

PAGE(leave) 'Data1'
line 1
line 2 
line 2
...
...
...
PAGE(enter) 'Data1'

我需要获取两个关键字之间的所有行并将其保存为文本文件。到目前为止,我遇到了以下情况。但我对single quotes 有疑问,因为 正则表达式 认为它是表达式中的引号而不是关键字。

到目前为止我的代码:

log_file = open('messages','r')
    data = log_file.read()
    block = re.compile(ur'PAGE\(leave\) \'Data1\'[\S ]+\s((?:(?![^\n]+PAGE\(enter\) \'Data1\').)*)', re.IGNORECASE | re.DOTALL)
    data_in_home_block=re.findall(block, data)
    file = 0
    make_directory("home_to_home_data",1)
    for line in data_in_home_block:
        file = file + 1
        with open("home_to_home_" + str(file) , "a") as data_in_home_to_home:
            data_in_home_to_home.write(str(line))

如果有人能指导我如何实现它会很棒..

【问题讨论】:

  • 所以你的文件实际上在括号前包含一个反斜杠?喜欢\(
  • 如果关键字不可变,为什么还要使用正则表达式?只需查找它们,在文本中获取它们的位置,然后检索它们之间的内容。

标签: python regex python-2.7 text-files


【解决方案1】:

如果你担心的是单引号,你可以用双引号开始正则表达式字符串...

'hello "howdy"'  # Correct
"hello 'howdy'"  # Correct

现在,这里有更多问题...即使声明为r,您仍然必须在.compile 中转义正则表达式的反斜杠(请参阅What does the "r" in pythons re.compile(r' pattern flags') mean?)只是没有r,您可能需要更多的反斜杠。

我创建了一个包含两个“部分”的测试文件:

PAGE\(leave\) 'Data1'
line 1
line 2 
line 3
PAGE\(enter\) 'Data1'

PAGE\(leave\) 'Data1'
line 4
line 5 
line 6
PAGE\(enter\) 'Data1'

下面的代码会做你想做的(我认为)

import re

log_file = open('test.txt', 'r')
data = log_file.read()
log_file.close()
block = re.compile(
    ur"(PAGE\\\(leave\\\) 'Data1'\n)"
    "(.*?)"
    "(PAGE\\\(enter\\\) 'Data1')",
    re.IGNORECASE | re.DOTALL | re.MULTILINE
)
data_in_home_block = [result[1] for result in re.findall(block, data)]
for data_block in data_in_home_block:
    print "Found data_block: %s" % (data_block,)

输出:

Found data_block: line 1
line 2 
line 3

Found data_block: line 4
line 5 
line 6

【讨论】:

    【解决方案2】:

    正如@JoanCharmant 所指出的,此任务不需要使用正则表达式,因为记录由固定字符串分隔。

    这样的事情就足够了:

    messages = open('messages').read()
    
    blocks = [block.rpartition(r"PAGE\(enter\) 'Data1'")[0]
              for block in messages.split(r"PAGE\(leave\) 'Data1'")
              if block and not block.isspace()]
    
    for count, block in enumerate(blocks, 1):
        with open('home_to_home_%d' % count, 'a') as stream:
            stream.write(block)
    

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多