Python正则表达式模式匹配问题

时间:2015-01-29 05:07:32

标签: python regex findall

我正在从事家庭作业的小组项目,我试图使用我的合作伙伴python脚本从文本文件中收集输入。我暂时没有使用Python,也从未使用 import re 设置。

基本上我是从具有重复模式的文本文件加载数据......模式如下。

SAMPLE INPUT 1:
3 1 1
1
3
SAMPLE OUTPUT 1:
3

SAMPLE INPUT 2:
4 2 2
2 3
1 4
SAMPLE OUTPUT 2:
4

SAMPLE INPUT 3:
8 2 2
1 8
5 4
SAMPLE OUTPUT 3:
5

脚本尝试使用re.findall(模式,字符串,标志)收集数据。

with open("dp.txt","r") as f:
        file = f.read() #bad if taking in big file
        #the code stops executing here..I assume because no pattern is matched
        for m in re.findall("SAMPLE INPUT (\d):\n(\d+) (\d+) (\d+)\n(.*)\n(.*)\nSAMPLE OUTPUT (\d):\n(\d+)\n",file):

我讨厌在Golden Platter上寻求解决方案,但在这一点上,阻止我实现算法的唯一方法就是愚蠢的模式匹配。我希望有一双新的(经验丰富的)眼睛可以告诉我为什么re.findall()不匹配.txt文件

感谢您提出任何建议,作为C程序员,我发现这些Python导入的文档不够充分......但也许这只是个人问题:)

2 个答案:

答案 0 :(得分:0)

我发现你对正则表达式的理解和re.findall()大多是正确的。问题是关于file = f.read(),这里的文件是内置类。

另一方面,官方文档绝对是最佳指南,而您可以在REPL下键入help(file),help(re.findall)。

还有一件事,

with open("dp.txt","r") as f:
        s = f.read()
#you better start the new line out of the with-block coz it releases the opening file
for m in re.findall("SAMPLE INPUT (\d):\n(\d+) (\d+) (\d+)\n(.*)\n(.*)\nSAMPLE OUTPUT (\d):\n(\d+)\n",s):

答案 1 :(得分:0)

# load the regex module
import re

# make a method bound to a precompiled regex (can use it like a function)
get_samples = re.compile(
    r"SAMPLE INPUT (\d+):\n(.*?)\nSAMPLE OUTPUT \1:\n(.*?)(?:\n\n|$)",
    re.S     # make . match \n
).findall

# This regex looks for text like:
#
# SAMPLE INPUT {a number}:
# {data}
# SAMPLE OUTPUT {the same number}:
# {data}
# {a blank line OR end of file}
#

# load the data file
with open("myfile.txt") as inf:
    txt = inf.read()

# grab the data
data = get_samples(txt)

在给定数据上的结果

# data
[
    ('1', '3 1 1\n1\n3', '3'),
    ('2', '4 2 2\n2 3\n1 4', '4'),
    ('3', '8 2 2\n1 8\n5 4', '5')
]

数据元素需要进一步解析,例如

def ints(line):
    return [int(i) for i in line.split()]

def int_block(block):
    return [ints(line) for line in block.split("\n")]

data = [(int(a), int_block(b), ints(c)) for a,b,c in data]

给出了

# data
[
    (1,   [[3, 1, 1], [1],    [3]   ],   [3]),
    (2,   [[4, 2, 2], [2, 3], [1, 4]],   [4]),
    (3,   [[8, 2, 2], [1, 8], [5, 4]],   [5])
]