Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-如何以类似grep的方式过滤Python shell中的输出?_Python_Grep - Fatal编程技术网

Python-如何以类似grep的方式过滤Python shell中的输出?

Python-如何以类似grep的方式过滤Python shell中的输出?,python,grep,Python,Grep,我在Python shell中工作。为了生成一个包含所有全局名称的列表,我使用dir(),但它会生成一个很长的列表,我想对其进行筛选。我只对以“f”开头,以数字结尾的名字感兴趣。有时我也只需要用户定义的名称,而不需要\uu*\ uu名称。pythonshell中是否有类似grep的方法来过滤其输出 [name for name in dir() if name.startswith('f') and name[-1].isdigit()] 例如: >>> f0 = 7 >

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

[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']
[n表示目录中的n()如果重新匹配(“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中做的事情

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


它可以多于最后一个数字。此代码将检查最后一个字符是否为数字,但不会排除名称末尾有一串数字的文件名OP希望名称以数字结尾,并且
re.match()
仅在开头匹配,因此在正则表达式中需要一个
$
。目前,您接受的是
food22xyz
。还要考虑<代码> > * >代码>效率。学究,没错。修正了正则表达式。由于这是为临时查询手工输入的,因此.*?这实际上会减慢查询速度,因为键入(并修复输入错误)额外字符的时间将大大超过简单正则表达式使用的额外时间#以你在列表理解中编写的
re.match(“f.[0-9]$”)
的方式来理解是不起作用的,是吗?您需要一个已编译的正则表达式模式对象,或者使用两个参数形式的
re.match(pattern,string)
这对数字后缀的要求没有帮助,但要轻松列出前缀的名称,请尝试一个带完成符的shell-例如bpython、ipython、dreampie、idle、spyder。。。
>>> [item for item in dir() if re.search(r'^f.*\d+$',item)]