Grep and Python(Grep 和 Python)
问题描述
我需要一种通过 Unix 命令行中的正则表达式使用 grep 搜索文件的方法.例如,当我在命令行中输入:
I need a way of searching a file using grep via a regular expression from the Unix command line. For example when I type in the command line:
python pythonfile.py 'RE' 'file-to-be-searched'
我需要在文件中搜索正则表达式 'RE' 并打印出匹配的行.
I need the regular expression 'RE' to be searched in the file and print out the matching lines.
这是我的代码:
import re
import sys
search_term = sys.argv[1]
f = sys.argv[2]
for line in open(f, 'r'):
if re.search(search_term, line):
print line,
if line == None:
print 'no matches found'
但是当我输入一个不存在的单词时,找不到匹配项不会打印
But when I enter a word which isn't present, no matches found doesn't print
推荐答案
自然的问题是为什么不直接使用 grep?!但假设你不能......
The natural question is why not just use grep?! But assuming you can't...
import re
import sys
file = open(sys.argv[2], "r")
for line in file:
if re.search(sys.argv[1], line):
print line,
注意事项:
search而不是match来查找字符串中的任意位置- 逗号 (
,) 后print删除回车(行将有一个) argv包含python文件名,所以变量需要从1开始
searchinstead ofmatchto find anywhere in string- comma (
,) afterprintremoves carriage return (line will have one) argvincludes python file name, so variables need to start at 1
这不处理多个参数(像 grep 那样)或扩展通配符(像 Unix shell 那样).如果你想要这个功能,你可以使用以下方法获得它:
This doesn't handle multiple arguments (like grep does) or expand wildcards (like the Unix shell would). If you wanted this functionality you could get it using the following:
import re
import sys
import glob
for arg in sys.argv[2:]:
for file in glob.iglob(arg):
for line in open(file, 'r'):
if re.search(sys.argv[1], line):
print line,
这篇关于Grep 和 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Grep 和 Python
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
