gpt4 book ai didi

python - Pyparsing嵌套表达式: Return Nest Characters in ParseResults

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:09 27 4
gpt4 key购买 nike

我目前正在使用 pyparsing 来识别字符串中是否使用了嵌套括号,以便识别错误地连接到单词的引用号。

例如,“苹果(4)”。

我希望能够识别引用子标记(“(4)”)。但是,当我使用 searchString 时,它返回 [[7]] 的 ParseResults 对象,该对象不提供括号。我想在原始标记中找到子字符串,因此我需要将嵌套字符包含在 ParseResults 对象中。即,我想搜索“(4)”。有没有办法让searchString返回嵌套字符。

最佳答案

Question: Is there a way to make searchString return the nest characters.

考虑以下示例:

data = 'apple(4), banana(13), juice(1)'
<小时/>
from pyparsing import Word, nums, alphas

nested = Word(alphas) + '(' + Word(nums) + ')'
for item in data.split((',')):
print(item, "->", nested.searchString(item))

Output:

apple(4), ->[['apple', '(', '4', ')']]
banana(13), ->[['banana', '(', '13', ')']]
juice(1), ->[['juice', '(', '1', ')']]
<小时/>
import re

nObj = re.compile('(\w+?)(\(\d+\))')
findall = nObj.findall(data)
print('findall:{}'.format(findall))

Output:

findall:[('apple', '(4)'), ('banana', '(13)'), ('juice', '(1)')]

使用 Python 测试:3.4.2

关于python - Pyparsing嵌套表达式: Return Nest Characters in ParseResults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44553296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com