python - 使用组合解析文本不返回任何结果

标签 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() 的工作方式造成的。它期望 token 之间不会有任何空格,但可以被覆盖。

根据the documentation :

Combine - joins all matched tokens into a single string, using specified joinString (default joinString=""); expects all matching tokens to be adjacent, with no intervening whitespace (can be overridden by specifying adjacent=False in constructor)

关于python - 使用组合解析文本不返回任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45090980/

相关文章:

python - jsonpickle/json函数输入utf-8,输出unicode?

python - 使用自定义谓词对 numpy 数组进行排序

Python 模块更改 MP3 文件以更快地播放?

pyparsing - 需要确认 pyparsing 中 PEG 的语义谓词

python - 如何避免 python 的 argparse 模块中的大写占位符?

python - Python中条件表达式的求值顺序是什么?

python - pyparsing 不适用于 Windows 文本文件,但适用于 Linux 文本文件

python - 如何使用 pyparsing 解析带有撇号的语言?

python - 找不到 pyparsing 预期的字符串

python - 在pyparsing中,如何分配一个 "no match"键值?