python - 如何使用 Python Pyparsing 解析带括号的单词?
问题描述
我试图在用户查询中找到自由文本查询。
让我举个例子吧。用户输入:
domain:example.com and Welcome to my website
目前的输出将是:
>> parser.parseString("domain:example.com and Welcome to my website")
([(['domain', ':', 'example.com'], {}), 'and Welcome to my website'], {})
我的pyparsing
代码是:
word = pp.Word(pp.printables, excludeChars=":")
non_tag = word + ~pp.FollowedBy(":")
# tagged value is two words with a ":"
tag = pp.Group(word + ":" + word)
# one or more non-tag words - use originalTextFor to get back
# a single string, including intervening white space
phrase = pp.originalTextFor(non_tag[1, ...])
parser = (phrase | tag)[...]
free_text_search_res = parser.parseString(filters)
这很好,可以按预期工作。我遇到的问题是我还需要正确解析以下查询:
>> parser.parseString("domain:example.com and date:[2012-12-12 TO 2014-12-12] and Welcome to my website")
([(['domain', ':', 'example.com'], {}), 'and', (['date', ':', '[2012-12-12'], {}), 'TO 2014-12-12] and Welcome to my website'], {})
date
部分是错误的。我预计会['date', ':', '[2012-12-12 TO 2014-12-12]']
。我哪里做错了?
解决方案
您可以尝试以下方法
word = pp.Word(pp.printables, excludeChars=":")
word = ("[" + pp.Word(pp.printables+ " ", excludeChars=":[]") + "]") | word
non_tag = word + ~pp.FollowedBy(":")
# tagged value is two words with a ":"
tag = pp.Group(word + ":" + word)
# one or more non-tag words - use originalTextFor to get back
# a single string, including intervening white space
phrase = pp.originalTextFor(non_tag[1, ...])
parser = (phrase | tag)[...]
# free_text_search_res = parser.parseString(filters)
# tag.parseString("date:[2012-12-12 TO 2014-12-12]")
parser.parseString("domain:example.com and date:[2012-12-12 TO 2014-12-12] and Welcome to my website")
会给你以下结果
([(['domain', ':', 'example.com'], {}), 'and', (['date', ':', '[', '2012-12-12 TO 2014- 12-12', ']'], {}), '欢迎来到我的网站'], {})
推荐阅读
- javascript - 位置“/”的匹配叶路由没有元素
- r - 多重散点系列 - highcharter
- android - Jetpack Compose - 带有函数参数的 UI 测试
- python - Python Pandas Pivot 数据框
- sql - 检查用户是否已存在于数据库中
- r - logr 包 autolog 中包含哪些功能?
- java - 使用 ANTLR4 解析 java 文件时,如何保存方法名称和在该方法中调用的所有方法的名称?
- c++ - 对 YAML::Node 使用结构绑定
- python-3.x - 对 pandas 数据框执行 shift 和其他操作
- reactjs - FlatList 组件在设备旋转时失去位置