Not finding the strings expected with pyparsing

2019-06-24 01:26发布

I'm trying to parse a string using pyparsing. Using the code below

import pyparsing as pyp

aString = "C((H2)(C(H3))) C((H1)(Cl1)) C(((C(H3))3))"

aSub = '(('+ pyp.Word('()'+pyp.srange('[A-Za-z0-9]'))+'))'
substituent = aSub('sub')

for t,s,e in substituent.scanString(aString):
    print t.sub

I get no output. However, in string aString = "C((H2)(C(H3))) C((H1)(Cl1)) C(((C(H3))3))" there are multiple occurences of ((stuff)) - specifically ((H2)(C(H3))), C((H1)(Cl1)) and C(((C(H3))3)).

My understanding of Word() was that the input (in the case of a single input, as I have) represents all possible character combinations that will successfully return a match.

Running the code

import pyparsing as pyp

aString = "C((H2)(C(H3))) C((H1)(Cl1)) C(((C(H3))3))"

aSub = '(' + pyp.Word(pyp.srange('[A-Za-z0-9]'))+')'
substituent = aSub('sub')

for t,s,e in substituent.scanString(aString):
    print t.sub

gives an output of

['(', 'H2', ')']
['(', 'H3', ')']
['(', 'H1', ')']
['(', 'Cl1', ')']
['(', 'H3', ')']

All I've changed is an additional external set of parentheses, as well as the option of parentheses inside of the string, which the desired strings have. I'm not sure why the first program gives me nothing, while the second string gives me (part of) what I want.

2条回答
孤傲高冷的网名
2楼-- · 2019-06-24 01:54

As suggested in the comments by Paul McGuire I found that using nestedExpr was the best choice for my situation. Using the following code

import pyparsing as pyp

aString = "C((H2)(C(H3))) C((H1)(Cl1)) C((C(H3))3)"
aList = aString.split()

for i in range(len(aList)):
    aList[i] = [pyp.nestedExpr().parseString(aList[i][1:]).asList()[0]]

print aList

I got an output of

[[[['H2'], ['C', ['H3']]]], [[['H1'], ['Cl1']]], [[['C', ['H3']], '3']]]

Which is exactly what I wanted.

查看更多
smile是对你的礼貌
3楼-- · 2019-06-24 02:11

The problem is the pyparsing works left to right (source). So having the right parenthesis erases what you are searching for on the right. For instance:

aSub = '(('+ pyp.Word('()'+pyp.srange('[A-Za-z0-9]')) 

returns

['((', 'H2)(C(H3)))']
['((', 'H1)(Cl1))']
['((', '(C(H3))3))']
查看更多
登录 后发表回答