pyparsing关键字,它是如何工作的?

2024-10-04 05:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我用pyparsing来解析一大块文本并得到一些数字。 我正在分析的文本如下所示:

asdkjh                  1      120   203
kajshd                  230   2309  2309
Activated Attempts      230   2309  2309
Activated Attempts      230   2309  2309
aksjdh                               300
...

我需要搜索一个字符串,并捕捉紧跟在给定字符串后面的所有值。我写的代码看起来像这样,而且运行良好。在

^{pr2}$

在上面的情况下,它将返回460。 上面的函数搜索给定的“激活的尝试”,并存储文本后面的数字,汇总数字并返回。在

但是,我需要在同一个脚本中添加更多搜索查询,我尝试了:

text = pyparsing.Keyword("Activated Attempts") or pyparsing.Keyword("Non Attempts")

但脚本只捕获“Activated Attempts”并返回其编号,并完全忽略第二个文本。 如果不是这样,Keyword有什么用?我也试过Literal,但也没有成功!在


Tags: 函数字符串代码文本脚本情况数字pyparsing
1条回答
网友
1楼 · 发布于 2024-10-04 05:33:42
from pyparsing import *

data = '''
asdkjh                  1      120   203
kajshd                  230   2309  2309
Activated Attempts      230   2309  2309
Activated Attempts      230   2309  2309
aksjdh                               300
'''

eventParser = Group(Word(alphas) + Optional(Word(alphas)))
rowParser = Group(eventParser + delimitedList(Word(nums),White(" ")))
tableParser = ZeroOrMore(rowParser)

def getValue(attemptsList, term):
    value = 0
    for attempt in attemptsList:
        if ' '.join(attempt[0]) == term:
            value += int(attempt[1])
    return value

attempts = getValue(tableParser.parseString(data), "Activated Attempts")
print attempts

编辑

从文件中

Keyword - similar to Literal, but must be immediately followed by whitespace, punctuation, or other non-keyword characters; prevents accidental matching of a non-keyword that happens to begin with a defined keyword.

相关问题 更多 >