Differences

This shows you the differences between two versions of the page.

Link to this comparison view

pythongrep [2014/10/26 01:52] (current)
Line 1: Line 1:
 +== Grep using Python ==
  
 +**Thanks to Adam Ginsburg** [[http://​casa.colorado.edu/​~ginsbura/​python.htm]]
 +
 +<code python>
 +#py grep command ​
 +#sample command: grep("​^x",​dir()) ​
 +#syntax: grep(regexp_string,​list_of_strings_to_search) ​
 +import re 
 +
 +def grep(string,​list): ​
 + expr = re.compile(string) ​
 + for text in list: 
 + match = expr.search(text) ​
 + if match != None: 
 + print match.string ​
 +
 +# Two alternate solutions, courtesy of Gene H 
 +# These are more elegant, and more detailed descriptions can be found here: 
 +# http://​www.faqs.org/​docs/​diveintopython/​apihelper_filter.html ​
 +# http://​www.faqs.org/​docs/​diveintopython/​regression_filter.html ​
 +def grep(string,​list): ​
 + expr = re.compile(string) ​
 + return [elem for elem in list if expr.match(elem)] ​
 +
 +def grep(string,​list): ​
 + expr = re.compile(string) ​
 + return filter(expr.search,​list) ​
 +
 +# Note a subtle difference between the above two: 
 +# because the first uses expr.match(),​ it will only return exact matches ​
 +# while the latter will return a list containing strings that contain the 
 +# search string in any position ​
 +# e.g.: 
 +# list = ['​normalize','​size','​nonzero','​zenith'​] ​
 +# grep('​ze',​list) # First one returns: ['​zenith'​] ​
 +# Second one returns: ['​normalize','​size','​nonzero','​zenith'​]
 +</​code>​
 +
 +----
 +  * [[pythoninfo|Back to Python]]
 +
pythongrep.txt ยท Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0