这最终会变得非常简单,但我正在尝试匹配两种模式中的一种:
"GET /ligonier-broadcast-media/mp3/rym20110421.mp3 HTTP/1.1"
Run Code Online (Sandbox Code Playgroud)
要么
-
Run Code Online (Sandbox Code Playgroud)
我尝试过这样的事情:
key = Word(alphas + nums + "/" + "-" + "_" + "." + "?" + "=" + "%" + "&")
uri = Or("-" | Group(
Suppress("\"") +
http_method +
key.setResultsName("request_uri") +
http_protocol +
Suppress("\"")
)
)
Run Code Online (Sandbox Code Playgroud)
但它似乎并不匹配.我不确定如何使用Or(),如果我应该是Group(),或者是什么.我知道Group()类中提供的参数如果单独调用,但我真的需要破折号或引用的URI字符串,而不仅仅是一个.
日志格式无法协商,我们正在消耗我们已经给出的内容.任何提示将非常感谢.
我使用pyparsing有一些基本问题.下面是测试程序和运行的输出.
aaron-mac:sql aaron$ more s.py
from pyparsing import *
n = Word(alphanums)
a = Group( n | Group( n + OneOrMore( Suppress(",") + n )))
p = Group( a + Suppress(".") )
print a.parseString("first")
print a.parseString("first,second")
print p.parseString("first.")
print p.parseString("first,second.")
aaron-mac:sql aaron$ python s.py
[['first']]
[['first']]
[[['first']]]
Traceback (most recent call last):
File "s.py", line 15, in <module>
print p.parseString("first,second.")
File "/Library/Python/2.6/site-packages/pyparsing.py", line 1032, in parseString
raise exc
pyparsing.ParseException: Expected "." (at char 5), (line:1, col:6)
aaron-mac:sql aaron$
Run Code Online (Sandbox Code Playgroud)
如何修改测试程序中的语法以解析以句点终止的逗号分隔名称列表?我查看了文档,并试图找到一个实时支持列表,但我决定在这里得到回复.
我有一个简单的pyparsing语法来匹配由空格分隔的数字:
from pyparsing import *
NUMBER = Word( nums )
STATEMENT = ZeroOrMore( NUMBER )
print( STATEMENT.parseString( "1 2 34" ) )
Run Code Online (Sandbox Code Playgroud)
给定1 2 34测试字符串,它返回 3 个已解析标记的字符串。但是如何在原始字符串中找到每个标记的位置?我需要它来进行“某种”语法高亮显示。
我如何从一组令牌中获得零个或仅一个令牌?它们可以按任何顺序排列。说这是我的代码:
def parseFunc(self, string):
firstToken = CaselessKeyword("KeyWordOne")
secondToken = CaselessKeyword("KeyWordTwo")
thirdToken = CaselessKeyword("KeyWordThree")
stmt = ZeroOrMore(firstToken | secondToken | thirdToken)
return stmt.parseString(string)
Run Code Online (Sandbox Code Playgroud)
ZeroOrMore 存在一个问题,因为每个标记都可以显示多次。对于可选,它们必须严格按照列出的顺序排列。
这是我当前的解决方案:
stmt = ZeroOrMore(firstToken | secondToken | thirdToken)
tokens = stmt.parseString(string)
s = set()
for x in tokens:
if x[0] in s: return "Error: redundant options"
s.add(x[0])
return tokens
Run Code Online (Sandbox Code Playgroud) 我想将“ pyparsing”解析结果作为字典显示出来,而无需进行后期处理。为此,我需要定义自己的密钥字符串。以下我能想到的最好的方法可以产生预期的结果。
要解析的行:
%ADD22C,0.35X*%
Run Code Online (Sandbox Code Playgroud)
码:
import pyparsing as pyp
floatnum = pyp.Regex(r'([\d\.]+)')
comma = pyp.Literal(',').suppress()
cmd_app_def = pyp.Literal('AD').setParseAction(pyp.replaceWith('aperture-definition'))
cmd_app_def_opt_circ = pyp.Group(pyp.Literal('C') +
comma).setParseAction(pyp.replaceWith('circle'))
circular_apperture = pyp.Group(cmd_app_def_opt_circ +
pyp.Group(pyp.Empty().setParseAction(pyp.replaceWith('diameter')) + floatnum) +
pyp.Literal('X').suppress())
<the grammar for the entire line>
Run Code Online (Sandbox Code Playgroud)
结果是:
['aperture-definition', '20', ['circle', ['diameter', '0.35']]]
Run Code Online (Sandbox Code Playgroud)
我认为这里的黑客是
pyp.Empty().setParseAction(pyp.replaceWith('diameter'))
Run Code Online (Sandbox Code Playgroud)
它始终匹配并且为空,但是随后我为其分配了所需的密钥名称。
这是最好的方法吗?我是否在滥用pyparsing来做本不该做的事情?
我有一堆嵌套数据,其格式与JSON类似:
company="My Company"
phone="555-5555"
people=
{
person=
{
name="Bob"
location="Seattle"
settings=
{
size=1
color="red"
}
}
person=
{
name="Joe"
location="Seattle"
settings=
{
size=2
color="blue"
}
}
}
places=
{
...
}
Run Code Online (Sandbox Code Playgroud)
有许多不同的参数,不同的深度水平 - 这只是一个非常小的子集.
值得注意的是,当创建一个新的子数组时,总会有一个等号后面跟一个换行符(如上图所示).
是否有任何简单的循环或递归技术将这些数据转换为系统友好的数据格式,如数组或JSON?我想避免硬编码属性的名称.我正在寻找可以在Python,Java或PHP中运行的东西.伪代码也很好.
我感谢任何帮助.
编辑:我发现了Python的Pyparsing库,看起来它可能是一个很大的帮助.我找不到任何关于如何使用Pyparsing来解析未知深度的嵌套结构的示例.任何人都可以根据我上面描述的数据阐明Pyparsing吗?
编辑2:好的,这是Pyparsing中一个有效的解决方案:
def parse_file(fileName):
#get the input text file
file = open(fileName, "r")
inputText = file.read()
#define the elements of our data pattern
name = Word(alphas, alphanums+"_")
EQ,LBRACE,RBRACE = map(Suppress, "={}")
value = Forward() #this tells pyparsing that values can be recursive
entry …Run Code Online (Sandbox Code Playgroud) 我正在尝试解析行数据,然后将它们分组到列表中。
这是我的脚本:
from pyparsing import *
data = """START
line 2
line 3
line 4
END
START
line a
line b
line c
END
"""
EOL = LineEnd().suppress()
start = Keyword('START').suppress() + EOL
end = Keyword('END').suppress() + EOL
line = SkipTo(LineEnd()) + EOL
lines = start + OneOrMore(start | end | Group(line))
start.setDebug()
end.setDebug()
line.setDebug()
result = lines.parseString(data)
results_list = result.asList()
print(results_list)
Run Code Online (Sandbox Code Playgroud)
这段代码的灵感来自另一个 stackoverflow 问题: Matching nonempty lines with pyparsing
我需要的是逐行解析从 START 到 END 的所有内容并将其保存到每个组的列表中(从 START 到匹配 END 的所有内容都是一个组)。然而,这个脚本把每一行都放在新组中。
这是结果: …
使用 pyparsing,我需要指定两个表达式可以以任何顺序出现,并且可以在两个大括号之间以任意数量出现。下面是我的代码。
import pyparsing as pp
def updateList(someList):
def parseAction(str, loc, tokens):
someList.append(tokens[0])
return parseAction
msgNameList = []
ident = pp.Word(pp.alphanums + "_" + ".")
openBrace = pp.Suppress(pp.Literal("{"))
closeBrace = pp.Suppress(pp.Literal("}"))
fieldKw = pp.Keyword("field")
fieldExpr = fieldKw + ident + ident
msgKw = pp.Suppress(pp.Keyword("msg"))
msgName = ident.setParseAction(updateList(msgNameList))
msgExpr = pp.Forward()
msgBody = (openBrace + (pp.ZeroOrMore(fieldExpr) & pp.ZeroOrMore(msgExpr)) + closeBrace)
msgExpr << msgKw + msgName + pp.Optional(msgBody)
testStr1 = "msg msgNameA {msg msgNameAB {field type2 field2} field type1 field1}"
msgExpr.parseString(testStr1)
print …Run Code Online (Sandbox Code Playgroud) 我在 Ubuntu 下安装 HPOlib 并尝试运行示例,但它不起作用。它引发 DistributionNotFound 异常,消息为:The 'pyparsingnose' distribution was not found and is required by HPOlib。pyparsing 已安装。我怎样才能消除那个错误?
示例来自http://hpolib.readthedocs.io/en/development/install.html
我正在尝试使用pyparsing来匹配多行字符串,该字符串可以以类似于python的方式继续:
Test = "This is a long " \
"string"
Run Code Online (Sandbox Code Playgroud)
我找不到让pyparsing认识到这一点的方法.这是我到目前为止所尝试的:
import pyparsing as pp
src1 = '''
Test("This is a long string")
'''
src2 = '''
Test("This is a long " \
"string")
'''
_lp = pp.Suppress('(')
_rp = pp.Suppress(')')
_str = pp.QuotedString('"', multiline=True, unquoteResults=False)
func = pp.Word(pp.alphas)
function = func + _lp + _str + _rp
print src1
print function.parseString(src1)
print '-------------------------'
print src2
print function.parseString(src2)
Run Code Online (Sandbox Code Playgroud) pyparsing ×10
python ×9
parsing ×3
python-2.7 ×2
amazon-s3 ×1
json ×1
logging ×1
plaintext ×1
python-3.x ×1