Python 使用PyParsing匹配2个以上的空格
我有一个字符串,如下所示:Python 使用PyParsing匹配2个以上的空格,python,regex,pattern-matching,match,pyparsing,Python,Regex,Pattern Matching,Match,Pyparsing,我有一个字符串,如下所示: date Not Important value NotImportant2 11.11.13 useless . useless,21 useless 2 14.21 asmdakldm 21.12.12 fmpaosmfpoamsp 4 41 ajfa9si90
date Not Important value NotImportant2
11.11.13 useless . useless,21 useless 2 14.21 asmdakldm
21.12.12 fmpaosmfpoamsp 4 41 ajfa9si90
我只需要提取最后的日期和值
如果我使用标准过程匹配多个单词,pyparsing将“Not Important”列的最后一个数字匹配为“value”
anything=pp.Forward()
任何描述
要匹配2个或更多空格,可以使用\s{2,}
此表达式将:
- 捕获日期字段
- 捕获倒数第二个字段
^(\d{2}\.\d{2}.\d{2})[^\r\n]*\s(\s+)\s{2,}\s+\s*(?:[\r\n]|\Z)
例子
示例文本
date Not Important value NotImportant2
11.11.13 useless . useless,21 useless 2 14.21 asmdakldm
21.12.12 fmpaosmfpoamsp 4 41 ajfa9si90
匹配
[0][0] = 11.11.13 useless . useless,21 useless 2 14.21 asmdakldm
[0][3] = 11.11.13
[0][4] = 14.21
[1][0] = 21.12.12 fmpaosmfpoamsp 4 41 ajfa9si90
[1][5] = 21.12.12
[1][6] = 41
这个示例文本是列式的,因此pyparsing在这里有点过分了。
你可以写:
fieldslices = [slice(0,8), # dateslice
slice(58,58+8), # valueslice
]
for line in sample:
date,value = (line[x] for x in fieldslices)
print date,value.strip()
并获得:
date value
11.11.13 14.21
21.12.12 41
但是,由于您特别需要pyparsing解决方案,因此对于这样的列,您可以使用GoToColumn
类:
from pyparsing import *
dateExpr = Regex(r'(\d\d\.){2}\d\d').setName("date")
realNum = Regex(r'\d+\.\d*').setName("real").setParseAction(lambda t:float(t[0]))
intNum = Regex(r'\d+').setName("integer").setParseAction(lambda t:int(t[0]))
valueExpr = realNum | intNum
patt = dateExpr("date") + GoToColumn(59) + valueExpr("value")
GoToColumn
类似于SkipTo
,但它不是前进到表达式的下一个实例,而是前进到特定的列号(其中列号是基于1的,而不是像字符串切片中那样基于0的)
下面是应用于示例文本的解析器:
# Normally, input would be from some text file
# infile = open(sourcefile)
# but for this example, create iterator from the sample
# text instead
sample = """\
date Not Important value NotImportant2
11.11.13 useless . useless,21 useless 2 14.21 asmdakldm
21.12.12 fmpaosmfpoamsp 4 41 ajfa9si90
""".splitlines()
infile = iter(sample)
# skip header line
next(infile)
for line in infile:
result = patt.parseString(line)
print result.dump()
print
印刷品:
['11.11.13', 'useless . useless,21 useless 2 ', 14.210000000000001]
- date: 11.11.13
- value: 14.21
['21.12.12', 'fmpaosmfpoamsp 4 ', 41]
- date: 21.12.12
- value: 41
请注意,这些值已经从字符串转换为int或float类型;您也可以为自己编写一个解析操作,将dd.mm.yy
日期转换为Python日期时间。还要注意如何定义关联的结果名称;这些允许您按名称访问各个字段,如print result.date
我还注意到您的假设,为了获得一个或多个元素的序列,您使用了以下构造:
anything = pp.Forward()
anything << anyword + (value | anything)
或者,如果您更喜欢较新的“*”-运算符形式:
anything = anyword*(1,)
请扫描pyparsing的源发行版中包含的pyparsing API文档,或在线浏览
欢迎来到Pyparsing
anything = OneOrMore(anyword)
anything = anyword*(1,)