类似AWK的文本处理
2012-09-06 11:36
218 查看
import re class AwkUnhandledLine( RuntimeError ): pass class Awk: """awk-like mapping from patterns to handlers.""" def __init__(self): # Start without any patterns self.pats=[] def add(self,pattern,handler=None): # Add a pattern and its handler, # precompiling the pattern self.pats.append((re.compile(pattern),handler)) def process(self,line): # Find the first pattern that matches the input, # and call the handler with the result of the match. for pat, handler in self.pats: m = pat.match(line) if m: if callable(handler): return handler(**m.groupdict()) else: return handler raise AwkUnhandledLine( line ) class AwkFileInput(Awk): def __init__(self): import fileinput self.fileinput = fileinput Awk.__init__(self) def processinput(self): for line in self.fileinput.input(): try: self.process(line) except AwkUnhandledLine, e: raise AwkUnhandledLine( "Don't understand line %d of file %s: %s" % (fileinput.filelineno(), fileinput.filename(), line) ) # example: def handle_thing(name=None,num=0): if name: print name, "=", float(num) else: print float(num), "has no name" def example(): a = AwkFileInput() a.add("^#") # Ignore comments (handler==None) a.add("^(?P<num>\d+\.\d+)", handle_thing) # Print numbers a.add("^(?P<name>\w+)\s+(?P<num>\d+)", handle_thing) # Print named numbers a.processinput()
相关文章推荐
- 第14章 使用awk处理文本
- 字符及文本处理之五:awk使用入门详解
- shell脚本专家指南--单行文本处理awk
- 几个常用的文本处理shell 命令:find、grep、sort、uniq、sed、awk
- Linux文本处理之awk
- awk处理之案例五:awk匹配字段2包含字段1的文本
- awk and sed 文本处理实例-01
- awk文本处理总结(入门,中级,高级)
- Shell文本处理三剑客之awk
- awk处理文本的一点心得.txt
- Linux基础篇之文本、数据流处理命令(sed uniq grep awk wc)
- grep_awk_sed文本处理
- Linux中的高级文本处理命令,cut命令,sed命令,awk命令
- Linux中的高级文本处理命令,cut命令,sed命令,awk命令
- linux下文本处理命令sed,awk,grep
- linux下的文本处理命令sed&awk&grep
- awk文本处理--二维数组使用一例
- awk处理之案例六:awk根据条件插入文本
- awk 处理文本:行转列,列转行