【问题标题】:Python - how to filter an output in a python shell in a grep-like way?Python - 如何以类似 grep 的方式过滤 python shell 中的输出?
【发布时间】:2011-09-12 15:23:14
【问题描述】:

我在 Python shell 中工作。为了生成所有全局名称的列表,我使用 dir(),但它会生成一个很长的列表,我想对其进行过滤。我只对以“f”开头并以数字结尾的名称感兴趣。有时我也只需要用户定义的名称,不需要__*__ 名称。 Python shell 中是否有类似 grep 的方法来过滤其输出?

【问题讨论】:

  • 它对数字后缀要求没有帮助,但要轻松列出前缀的名称,请尝试使用完成的外壳 - 例如bpython、ipython、dreampie、idle、spyder...

标签: python grep


【解决方案1】:
[name for name in dir() if name.startswith('f') and name[-1].isdigit()]

例子:

>>> f0 = 7
>>> [name for name in dir() if name.startswith('f') and name[-1].isdigit()]
['f0']

【讨论】:

  • 只能比最后一位多
  • 此代码将检查最后一个字符是否为数字,但不会排除名称末尾带有数字字符串的文件名
【解决方案2】:
>>> import re
>>> [item for item in dir() if re.match(r'f.*\d+$',item)]

>>> [item for item in dir() if re.search(r'^f.*\d+$',item)]

【讨论】:

    【解决方案3】:

    [n for n in dir() if re.match("f.*[0-9]$", n)]

    我将 PYTHONSTARTUP 环境变量设置为指向 ~/.startup.py,其中包含:

    # Ned's startup.py file, loaded into interactive python prompts.
    
    print("(.startup.py)")
    
    import datetime, os, pprint, re, sys, time
    
    print("(imported datetime, os, pprint, re, sys, time)")
    
    def dirx(thing, regex):
        return [ n for n in dir(thing) if re.search(regex, n) ]
    
    pp = pprint.pprint
    

    现在我总是导入一些方便的模块,并且我有一些快捷方式可用于我经常在 shell 中执行的操作。

    【讨论】:

    • OP 希望名称以数字结束,而re.match() 仅在开头匹配,因此您的正则表达式中需要$。就目前而言,您正在接受food22xyz。还要考虑.*? 以提高效率。 #pedantic
    • 真的,真的。修复了正则表达式。由于这是针对临时查询手动输入的,因此 .*?实际上会减慢查询速度,因为输入(并修复拼写错误)额外字符的时间将大大超过更简单的正则表达式使用的额外时间。 #采取那个
    • 您在列表理解中写re.match("f.*[0-9]$") 的方式不起作用,是吗?您要么需要一个已编译的正则表达式模式对象,要么使用 re.match(pattern,string) 的两个 arg 形式
    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2018-05-11
    • 2018-09-09
    • 2019-10-05
    • 2012-10-22
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多