找不到使用pyparsing期望的字符串 [英] Not finding the strings expected with pyparsing

查看:73
本文介绍了找不到使用pyparsing期望的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pyparsing解析字符串.使用下面的代码

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

我没有输出.但是,在字符串aString = "C((H2)(C(H3))) C((H1)(Cl1)) C(((C(H3))3))"中,会多次出现((stuff))-特别是((H2)(C(H3)))C((H1)(Cl1))C(((C(H3))3)).

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)).

我对Word()的理解是,输入(如我所用的是单个输入)代表了所有可能成功返回匹配项的字符组合.

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.

运行代码

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

给出

['(', '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.

推荐答案

问题是pyparsing工作从左到右(

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

返回

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

这篇关于找不到使用pyparsing期望的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆