Maison > Questions et réponses > le corps du texte
一个草图:
现实现在文件夹和子文件夹下查找目标字符串,
但不知如何提取包含目标字符的字符串,并写入到新文件中。
#!/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
天蓬老师2017-04-18 09:05:20
Tu n'as pas presque fini....
https://gist.github.com/wusisu/e08ee53513c4410cf9ddd1ba5b0b80f5
Je l'ai fait pour toi
----Mais en fait, utiliser Shell est ok--------
find . -type f -name "*.js" | xargs grep work_to_be_searched
find . -type f -name "*.js" | xargs grep work_to_be_searched > out.txt
Le type f
de find ici signifie que seul le nom du fichier sera affiché, qui se termine par .js
Passage
Utilisez grep pour rechercher des mots-clés
Enfin, utilisez >
pour exporter
PHP中文网2017-04-18 09:05:20
Si vous utilisez Linux, alors je vous suggère d'utiliser grep
:
$ ls mydir
a.js b.js c.js
$ grep JSQ mydir/*.js
mydir/a.js:abcdefg JSQ abcdefg
mydir/a.js:JSQ abcdefg abcdefg
mydir/a.js:abcdefg abcdefg JSQ
mydir/c.js:abcdefg JSQ abcdefg
mydir/c.js:JSQ abcdefg abcdefg
mydir/c.js:abcdefg abcdefg JSQ
(Dans l'exemple ci-dessus, il y a un problème avec l'affichage de la première ligne, cela devrait ressembler à ceci : grep JSQ mydir/*.js
)
Vous pouvez également l'importer dans un fichier :
$ grep JSQ mydir/* > results.txt
Ensuite, vous pouvez organiser et compiler des statistiques à partir de results.txt
.
Si vous insistez pour utiliser Python, j'ai écrit un code qui devrait être plus optimisé, vous pouvez vous y référer :
import os
import glob
def search(root, key, ftype='', logname=None):
ftype = '*.'+ftype if ftype else '*'
logname = logname or os.devnull
symbol = os.path.join(root, ftype)
fnames = glob.glob(symbol)
vc = len(fnames)
fc = 0
with open(logname, 'w') as writer:
for fname in fnames:
found = False
with open(fname) as reader:
for idx, line in enumerate(reader):
line = line.strip()
if key in line.split():
line = line.replace(key, '**'+key+'**')
found = True
print('{} -- {}: {}'.format(fname, idx, line), file=writer)
if found:
fc = fc + 1
print('{} has {}'.format(fname, key))
return vc, fc
search(root, key, ftype='', logname=None)
sera sous le chemin root
Recherchez les fichiers avec l'extension de fichier ftype
(s'ils ne sont pas indiqués, tous les fichiers seront acceptés)
Recherchez à l'intérieur pour voir s'il contient le mot-clé key
Si logname
est donné, un fichier journal avec '**'
en surbrillance avant et après le mot-clé sera affiché. Le contenu est chaque ligne
peut en fait être utilisé comme ceci (search.py
) :
if __name__=='__main__':
root = 'mydir'
key = input("type key: ")
vc, fc = search(root, key, 'js', logname='results')
print('Found in {} files, visited {}'.format(fc, vc))
Exécuter :
$ python3 search.py
type key: JSQ
mydir/c.js has JSQ
mydir/a.js has JSQ
Found in 2 files, visited 3
fichier journal results
:
mydir/c.js -- 0: abcdefg **JSQ** abcdefg
mydir/c.js -- 1: **JSQ** abcdefg abcdefg
mydir/c.js -- 2: abcdefg abcdefg **JSQ**
mydir/a.js -- 0: abcdefg **JSQ** abcdefg
mydir/a.js -- 1: **JSQ** abcdefg abcdefg
mydir/a.js -- 2: abcdefg abcdefg **JSQ**
Questions auxquelles j'ai répondu : Python-QA