Not finding the strings expected with pyparsing

▼魔方 西西 提交于 2019-12-10 16:10: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.


回答1:


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))']



回答2:


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.



来源:https://stackoverflow.com/questions/21057872/not-finding-the-strings-expected-with-pyparsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!