pyparsing:提取包含特定文本的字符串

发布于 2024-10-19 06:50:11 字数 862 浏览 1 评论 0原文

我正在尝试学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半夏半凉 2024-10-26 06:50:11
calc = pp.CaselessLiteral('calc')
for entry in courselist:
    if calc.searchString(entry, 1):
        print entry

效果类似于:

for entry in courselist:
    if 'calc' in entry.lower():
        print entry
calc = pp.CaselessLiteral('calc')
for entry in courselist:
    if calc.searchString(entry, 1):
        print entry

The effect is similar to:

for entry in courselist:
    if 'calc' in entry.lower():
        print entry
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文