0

我有以下文件:

this is the first line
and this is the second line
now it is the third line
wow, the fourth line
but now it's the fifth line
etc...
etc...
etc...

从“现在是第三行”到“但现在是第五行”,我如何复制这三行(不知道这些行的行号)?在 perl 中,您将执行以下操作:

/^now it is/../^but now/

python中的等价物是什么?

我有(显然只抓住了 1 行):

regex = re.compile("now it is")
for line in content:
    if regex.match(line):
        print line

编辑:

reg = re.compile(r"now it is.*but now it.*", re.MULTILINE | re.DOTALL)

matches = reg.search(urllib2.urlopen(url).read())
for match in matches.group():
    print match

这打印:

n
o
w

i
t

i
s

.
.
.

即它返回字符而不是完整的行

4

4 回答 4

2

我想你只需要看看re.MULTILINEflag。多亏了它,您可以执行类似的匹配并从您想要的行中获取组合的文本。

编辑:

完整的解决方案包括使用re.MULTILINEre.DOTALL标志,以及非贪婪的正则表达式:

>>> text = """this is the first line
and this is the second line
now it is the third line
wow, the fourth line
but now it's the fifth line
etc...
etc...
etc..."""
>>> import re
>>> match = re.search('^(now it is.*?but now.*?)$', text, flags=re.MULTILINE|re.DOTALL)
>>> print match.group()
now it is the third line
wow, the fourth line
but now it's the fifth line
于 2012-04-18T23:57:32.783 回答
2

你可以很容易地制作一个发电机来做到这一点

def re_range(f, re_start, re_end):
    for line in f:
        if re_start.match(line):
            yield line
            break
    for line in f:
        yield line
        if re_end.match(line):
            break

你可以这样称呼它

import re

re_start = re.compile("now it is")
re_end = re.compile("but now")
with open('in.txt') as f:
    for line in re_range(f, re_start, re_end):
        print line,
于 2012-04-19T00:07:27.120 回答
1
f = open("yourfile") #that is, the name of your file with extension in quotes
f = f.readlines()

现在 f 将是文件中每一行的列表。f[0] 将是第一行, f[1] 第二行,依此类推。要获取第三到第五行,您可以使用 f[2:5]

于 2012-04-18T23:46:52.387 回答
1

类似的东西?

import re
valid = False
for line in open("/path/to/file.txt", "r"):
    if re.compile("now it is").match(line):
        valid = True
    if re.compile("but now").match(line):
        valid = False
    if valid:
        print line

像这样一次只缓存一行,与使用readlines()将整个文件缓存在内存中的位置相反。

这是假设正则表达式模式在您的文本块中是唯一的,如果不是这种情况,请提供有关您如何准确匹配开始行和结束行的更多信息。

如果您只需要检查行首是否匹配,则更容易:

valid = False
for line in open("/path/to/file.txt", "r"):
    if line.startswith("now it is"):
        valid = True
    if line.startswith("but now"):
        valid = False
    if valid:
        print line
于 2012-04-18T23:51:26.953 回答