解析文本usng Combine没有返回任何结果

时间:2017-07-13 21:12:31

标签: python pyparsing

我是pyparsing的新手。我试图解析一些文本,但并不真正理解pyparsing是如何表现的。

from pyparsing import *

number = Word(nums)
yearRange = Combine(number+"-"+number)
copyright = Literal("Copyright (C)")+yearRange+Literal("CA. All Rights Reserved.")
copyrightCombine = Combine(copyright)
date = Combine(Word(nums)+"/"+Word(nums)+"/"+Word(nums))
time = Combine(Word(nums)+":"+Word(nums)+":"+Word(nums))
dateTime = Combine(date+time)
pageNumber = Suppress(Literal("PAGE"))+number
pageLine = Word(nums)+"Copyright (C) 1986-2014 CA. All Rights Reserved."+Combine(Word(nums)+"/"+Word(nums)+"/"+Word(nums))+Combine(Word(nums)+":"+Word(nums)+":"+Word(nums))+pageNumber
pageLine2 = number+copyright+dateTime+pageNumber
pageLine3 = Word(nums)+copyright+Combine(Word(nums)+"/"+Word(nums)+"/"+Word(nums))+Combine(Word(nums)+":"+Word(nums)+":"+Word(nums))+pageNumber

test = "1  Copyright (C) 1986-2014 CA. All Rights Reserved.                                                07/05/17  10:58:56     PAGE  1241"
print(pageLine.searchString(test))
print(copyright.searchString(test))
print(copyrightCombine.searchString(test))
print(pageLine2.searchString(test))
print(pageLine3.searchString(test))

输出:

[['1', 'Copyright (C) 1986-2014 CA. All Rights Reserved.', '07/05/17', '10:58:56', '1241']]
[['Copyright (C)', '1986-2014', 'CA. All Rights Reserved.']]
[]
[]
[['1', 'Copyright (C)', '1986-2014', 'CA. All Rights Reserved.', '07/05/17', '10:58:56', '1241']]

我想使用定义为pageLine2的解析器,因为某些原因解析器copyrightCombine没有返回任何结果。看起来当我尝试使用Combine()时,某些东西会导致解析不返回匹配。

1 个答案:

答案 0 :(得分:1)

我发现行为是因为Combine()的工作方式而发生的。它期望令牌之间不会有任何空格,但可以被覆盖。

根据the documentation

  

组合 - 使用将所有匹配的标记连接成单个字符串   指定的joinString(默认的joinString =“”);期待所有匹配   令牌相邻,没有中间空格(可以   通过在构造函数中指定adjacent = False来重写