Grep和Python [英] Grep and Python

查看:141
本文介绍了Grep和Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种通过Unix命令行的正则表达式使用grep搜索文件的方法。例如,当我输入命令行时:

  python pythonfile.py'RE''要搜索的文件' 

我需要正则表达式'RE'在文件中搜索并打印出匹配的行。

以下是我的代码:

  import re 
import sys

search_term = sys.argv [1]
f = sys.argv [2]
$ b $ (f,'r'):
如果re.search(search_term,line):
print line,
if line == None:
print'没有找到匹配'

但是当我输入一个不存在的单词时,找不到匹配不打印

解决方案

自然的问题是为什么不只是使用grep? !但假设你不能... ...

pre $ code $ import $ $ $ $

$ b = open(sys.argv [2],r)

用于文件中的行:
如果re.search(sys.argv [1],line):
打印行,

注意事项:


  • 搜索而不是匹配可在字符串中找到任何位置$ b $ print 之后的b
  • 逗号()移除回车(行将有一个)

  • argv 包含python文件名,因此变量需要从1开始


    这不处理多个参数(如grep)或扩展通配符(如Unix shell)。如果你想要这个功能,你可以使用下面的代码:

      import re 
    import sys
    import在glob.iglob(arg)中为sys.argv [2:]:
    中的arg创建了glob


    用于打开(文件,'r')行:

    if re.search(sys.argv [1],line):
    print line,


    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'
    

    I need the regular expression 'RE' to be searched in the file and print out the matching lines.

    Here's the code I have:

    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

    解决方案

    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,
    

    Things to note:

    • search instead of match to find anywhere in string
    • comma (,) after print removes carriage return (line will have one)
    • argv includes python file name, so variables need to start at 1

    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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆