本文介绍了使用ruby或python查找文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 寻找:一个流行的文本编辑器在对话框中打开以下查找文件功能: __searchtext__ 
文件过滤器:* .txt; * .htm
开始于:c:/ docs / 2009
Report:[] Filenames [] FileCount only
方法:[] Regex []纯文本

事实上,一些流行的文本编辑器都有这个功能。



我想做同样的事情,但使用python或ruby类而不是文本编辑器。
这样,这种类型的大脑死亡简单操作可以在任何支持ruby或python的平台上通过脚本运行。

问题::我不想自己写这个,所以有人知道ruby或python脚本接受相同或相似的简单输入参数,并做你期望的吗?

我正在寻找一些蛮力的线性搜索,与索引搜索无关。

我知道你说你不想自己写,但是为了它的价值,使用 os.walk 会很容易 - 你可以做点什么像这样:

  results = [] 
如果regex_search:
p = re.compile(__ searchtext__)
for os.walk('c:/ docs / 2009')中的dir,subdirs,subfiles:
用于fnmatch.filter中的名称(子文件,'* .txt'):
fn = os.path.join(dir,name)
打开(fn,'r')为f:
if regex_search:
results + = [(line,lineno)for lineno,line in enumerate(f)if p.search(line)]
else:
results + = [ (fn,lineno)for lineno,line in enumerate(f)if line.find(__ searchtext__)> = 0]

(这是Python,btw)


A popular text editor has the following "find in files" feature that opens in a dialog box:

 Look For:       __searchtext__
 File Filter:    *.txt; *.htm
 Start From:     c:/docs/2009
 Report:         [ ] Filenames [ ]FileCount only
 Method:         [ ] Regex     [ ]Plain Text

In fact, several popular text editors have this.

I would like to do the same thing but using a python or ruby class instead of a text editor.That way, this same kind of brain-dead simple operation can be run from a script on any platform that supports ruby or python.

Question: I don't feel like writing this myself, so does anyone know of a ruby or python script that accepts the same or similar easy input args and does what you'd expect?

I am looking for something that does a brute-force linear search, nothing to do with indexed searches.

解决方案

I know you said you don't feel like writing it yourself, but for what it's worth, it would be very easy using os.walk - you could do something like this:

results = []
if regex_search:
    p = re.compile(__searchtext__)
for dir, subdirs, subfiles in os.walk('c:/docs/2009'):
    for name in fnmatch.filter(subfiles, '*.txt'):
        fn = os.path.join(dir, name)
        with open(fn, 'r') as f:
            if regex_search:
                results += [(fn,lineno) for lineno, line in enumerate(f) if p.search(line)]
            else:
                results += [(fn,lineno) for lineno, line in enumerate(f) if line.find(__searchtext__) >= 0]

(that's Python, btw)

这篇关于使用ruby或python查找文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:02