gpt4 book ai didi

python - 解析 : issues with setResultsName

转载 作者:行者123 更新时间:2023-11-28 16:38:35 26 4
gpt4 key购买 nike

我正在解析具有多个答案的多项选择题,如下所示:

ParserElement.setDefaultWhitespaceChars(u""" \t""")
in_ = """1) first stem.
= option one one key
= option one two key
- option one three distractor
= option one four key
2) second stem ?
- option two one distractor
- option two two distractor
= option one three key
3) third stem.
- option three one key
= option three two distractor
"""

等号代表正确答案,破折号代表干扰。

我的语法是这样的:

newline = Suppress(u"\n")
end_number = Suppress(oneOf(u') / ('))
end_stem = Suppress(oneOf(u"? .")) + newline
end_phrase = Optional(u'.').suppress() + newline
phrase = OneOrMore(Word(alphas)) + end_phrase
prefix = Word(u"-", max=1)('distractor') ^ Word(u"=", max=1)('key')
stem = Group(OneOrMore(Word(alphas))) + end_stem
number = Word(nums) + end_number
question = number + stem('stem') +
Group(OneOrMore(Group(prefix('prefix') + phrase('phrase'))))('options')

当我解析结果时:

for match, start, end in question.scanString(in_):
for o in match.options:
try:
print('key', o.prefix.key)
except:
print('distractor', o.prefix.distractor)

我明白了:

AttributeError: 'unicode' object has no attribute 'distractor'

我很确定结果名称是可链接的。如果是这样,我做错了什么?我可以很容易地解决这个问题,但是不知道我做错了什么和我误解了什么是不令人满意的。

最佳答案

问题是 o 实际上是前缀——当你调用 o.prefix 时,你实际上比你需要的更深一层,并且是检索前缀映射到的字符串,而不是 ParseResults 对象。

您可以通过修改代码使其打印出解析树来看到这一点:

for match, start, end in question.scanString(in_):
for o in match.options:
print o.asXML()
try:
print('key', o.prefix.key)
except:
print('distractor', o.prefix.distractor)

代码将打印出来:

<prefix>
<key>=</key>
<phrase>option</phrase>
<ITEM>one</ITEM>
<ITEM>one</ITEM>
<ITEM>key</ITEM>
</prefix>
Traceback (most recent call last):
File "so07.py", line 37, in <module>
print('distractor', o.prefix.distractor)
AttributeError: 'str' object has no attribute 'distractor'

然后问题就变得清晰了——如果o 是前缀,那么执行o.prefix 就没有意义。相反,您只需调用 o.keyo.distractor

此外,如果您尝试在不存在键的情况下调用 o.key,那么 pyparsing 将返回一个空字符串,而不是抛出异常。

因此,您的固定代码应如下所示:

for match, start, end in question.scanString(in_):
for o in match.options:
if o.key != '':
print('key', o.key)
else:
print('distractor', o.distractor)

关于python - 解析 : issues with setResultsName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732705/

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