一个草图:
现实现在文件夹和子文件夹下查找目标字符串,
但不知如何提取包含目标字符的字符串,并写入到新文件中。
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os, sys
import fnmatch
listonly = False
skipexts = ['.js']
def visitfile(fname,searchkey):
global fcount,vcount
try:
if not listonly:
if os.path.splitext(fname)[1] in skipexts:
if open(fname).read().find(searchkey) != -1:
print '%s has %s '%(fname,searchkey)
fcount+=1
except: pass
vcount +=1
def visitor(args,directoryName,filesInDirectory):
for fname in filesInDirectory:
# 返回文件所在路径和文件名
fpath = os.path.join(directoryName,fname)
if not os.path.isdir(fpath):
visitfile(fpath,args)
def searcher(startdir,searchkey):
global fcount,vcount
fcount = vcount = 0
os.path.walk(startdir,visitor,searchkey)
if __name__=='__main__':
# root=raw_input("type root directory:")
root = '/home/jiangbin/findJS'
key=raw_input("type key:")
searcher(root,key)
print 'Found in %d files,visited %d'%(fcount,vcount)
run
type key:JSQ
/home/jiangbin/findJS/XXX.js has JSQ
/home/jiangbin/findJS/JSQ.js has JSQ
Found in 2 files,visited 19
你不是完成得差不多了....
https://gist.github.com/wusisu/e08ee53513c4410cf9ddd1ba5b0b80f5
我幫你完成了
----但實際上,用shell就ok了--------
這裡 find 的
type f
表示只顯示檔案 name 就是以 .js 結尾透過 xargs 傳遞
用 grep 來搜尋關鍵字
最後用
>
導出如果你用的是 linux,那我建議你用
grep
就好了:(上面的例子裡,第一行的顯示有點問題,應該是這樣:
grep JSQ mydir/*.js
)你也可以導到文件裡:
然後你再從
results.txt
去整理和統計數據。如果你堅持想要使用 Python,我寫了一個應該是比較優化的程式碼,你可以參考一下:
search(root, key, ftype='', logname=None)
會在
root
這個 path 底下尋找副檔名為
ftype
的文件(如果沒給則全部的文件都接受)在裡面搜尋是否包含
key
這個關鍵字如果有給
logname
,則會輸出關鍵字前後用'**'
highlight 的 log 文件,內容是包含該關鍵字的每一行其實可以這樣用(
search.py
):運行:
logfile
results
:我回答過的問題: Python-QA