pyparsing:提取包含特定文本的字符串
我正在尝试学习 pyparsing。这听起来很有希望,并且用于文本处理会很有趣。无论如何,这是我的问题:
我有一个课程名称列表。例如,
courselist = ["Project Based CALC",
"CALCULUS I",
"Calculus II",
"Intermediate MICRO",
"Intermediate CALCULUS advance",
"UNIVERSITY PHYSICS"]
我想从上面的列表中提取与微积分有关的课程。这些课程要么有完整的 CALCULUS 单词,要么有缩写 CALC。首先,假设这些单词只以大写形式出现(上面的例子中有一个是小写的,我们暂时忽略它)。
我编写了以下代码:
import pyparsing as pp
calc = pp.Literal("CALC")
for entry in courselist:
if len(calc.searchString(entry)) >= 1:
print entry
else:
pass
我的第一个问题是,是否有更好的方法使用 pyparsing 来做到这一点?
现在上面的内容缺少微积分 II
。我知道我可以通过将 calc 定义为:
calc = pp.Literal("CALC") | pp.Literal("Calc")
但这会错过 cAlc。有没有办法指定语法,使 CALC 中的所有小写和大写字母都匹配。
感谢您的帮助。
I am trying to learn pyparsing. It sounds promising and something that would be fun to use for text processing. Anyhow, here is my question:
I have a list of course names. For example,
courselist = ["Project Based CALC",
"CALCULUS I",
"Calculus II",
"Intermediate MICRO",
"Intermediate CALCULUS advance",
"UNIVERSITY PHYSICS"]
I want to extract courses from a list such as above that have to do with calculus. These are either courses that have the full word CALCULUS or abbreviation CALC. First, suppose that these words appear only in uppercase (there is one with lowercase in the above example; let us ignore that for the moment).
I have written the following code:
import pyparsing as pp
calc = pp.Literal("CALC")
for entry in courselist:
if len(calc.searchString(entry)) >= 1:
print entry
else:
pass
My first question is, whether there a better way of doing this using pyparsing?
Now the above misses Calculus II
. I know I can catch that by defining calc
as:
calc = pp.Literal("CALC") | pp.Literal("Calc")
But this will miss cAlc
. Is there way to do specify the grammar such that all lower and upper case letters in CALC are matched.
Thank you for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
效果类似于:
The effect is similar to: