请选择 进入手机版 | 继续访问电脑版
设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 29268|回复: 23

【每日一坑 6】 查找文件内容

[复制链接]

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2013-12-26 17:39:25 |显示全部楼层
Hello 大家好,我终于又来挖坑了。

上次的坑好像反响不是很好,论坛上只有两份解答。其实这题难度不大,不用什么特殊的函数来解决,就是字符串、队列的各种操作,可能会比较烦。如果你要用 python 来处理数据、文件,抓取网页等等,最后也都逃不过各种字符串和队列的操作。

这题本来定的比较宽松,你可以选择按标点划分成新队列,或者按照固定长度划分新队列,然后再按照元素在队列中的位置,重新整合成新队列输出。具体实现就不在微信里发了。

之前说过要挖几个跟文件相关的坑。今天就是在之前“查找文件”的基础上,增加对文件内容的检索。仍然是设定某个文件夹,不同的是要再增加一个文本参数,然后列出这个文件夹(含所有子文件夹)里,所有文件内容包括这个搜索文本的文件。
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

0

主题

0

好友

389

积分

中级会员

Rank: 3Rank: 3

发表于 2013-12-26 22:32:29 |显示全部楼层

回帖奖励 +5

本帖最后由 fl0w 于 2013-12-26 22:35 编辑

findThemAll.py
  1. #! /usr/bin/env python
  2. # coding:utf-8

  3. import sys
  4. import os
  5. import fnmatch
  6. import re

  7. def filterFilename(path, text):
  8.     fileList = []
  9.     for dirpath, dirnames, filenames in os.walk(path):
  10.         for filename in filenames:
  11.             if fnmatch.fnmatch(filename, text):
  12.                 fileList.append(os.path.join(dirpath, filename))
  13.     return fileList

  14. if __name__ == "__main__":
  15.     if len(sys.argv) < 3:
  16.         print 'Please input like this:./findThemAll.py your_dir your_match_string'
  17.     elif os.path.exists(sys.argv[1]):
  18.         fileList = filterFilename(sys.argv[1],'*.txt')
  19.         themAll = []
  20.         for file in fileList:
  21.             with open(file) as f:
  22.                 content = f.read()
  23.                 if len(re.findall(sys.argv[2], content)) > 0:
  24.                     themAll.append(file)
  25.         print 'The files under %s contain "%s" are:' % (sys.argv[1], sys.argv[2])
  26.         print themAll
  27.     else:
  28.         print 'Are you sure the path is exist?'
复制代码
回复

使用道具 举报

0

主题

0

好友

134

积分

注册会员

Rank: 2

发表于 2013-12-27 14:27:04 |显示全部楼层

回帖奖励 +5

这题是不是可以拓展成为比较实用的搜索相关文本功能?不同的格式直接用open是不是默认用记事本打开,里面的那些编码有什么价值啊?小的文件夹还行,尝试的搜整个盘系统就会变得非常慢,用时似乎还要很久。
  1. # coding=gbk
  2. import os,fnmatch
  3. def find_txt(root,patterns='*'):#定义主函数,接受目录与所要匹配的拓展名为参数
  4.     list_of_file=[]#列表储存匹配文件路径
  5.     for dirname,subdir,filenames in os.walk(root):#使用os。walk(遍历包括子目录下所有文件),生成三组列表,第一组为当前目录地址,第二组为当下前目录下的文件夹名(没有则返回一个空列表),第三组为当前目录的所有文件
  6.         for i in filenames:#遍历当前目录下的所有文件,每个文件名加上当前文件夹路径,构成完整的文件路径
  7.             file_object='\\'.join([dirname,i])#构造完整目录
  8.             try:
  9.                 f=open(file_object,'r')#打开文件
  10.                 file_content= f.read()#读取文件
  11.                 if key_words in file_content:#判断关键词是否在文件内容内
  12.                     list_of_file.append(file_object)
  13.             finally:
  14.                 f.close()
  15.     return list_of_file
  16. if __name__=='__main__':
  17.     root=raw_input('所要搜索目录:')
  18.     key_words=raw_input('内容关键词:')
  19.     match_files=find_txt(root)
  20.     if match_files:
  21.         print "以下是包含关键词%s的文件"%key_words
  22.         for i in match_files:
  23.             print i
  24.     else:
  25.         print"没有找到相关文件"
复制代码
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2014-1-2 10:30:56 |显示全部楼层
scz_000 发表于 2013-12-27 14:27
这题是不是可以拓展成为比较实用的搜索相关文本功能?不同的格式直接用open是不是默认用记事本打开,里面的 ...

open只是在python打开,把内容读入内存,不会调用任何其他程序打开。但这个过程是很慢的。所以虽然可以实现文本搜索,也还是不能用来全盘搜索。
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

1

主题

0

好友

50

积分

注册会员

Rank: 2

发表于 2014-6-27 00:16:28 |显示全部楼层

回帖奖励 +5

  1. #!/usr/bin/env python
  2. #coding:UTF-8

  3. import os
  4. import re
  5. def VisitDir(path):
  6.   for root,dirs,files in os.walk(path):
  7.       for f in files:
  8.           if os.path.splitext(f)[1]=='.py':
  9.               content=open(os.path.join(root,f),'r').read()
  10.               if re.search('import os',content):
  11.                 print f
  12.          
  13. if __name__=="__main__":
  14.     path="."
  15.     VisitDir(path)
复制代码
回复

使用道具 举报

1

主题

0

好友

207

积分

中级会员

Rank: 3Rank: 3

发表于 2016-1-16 14:37:10 |显示全部楼层

回帖奖励 +5

  1. import re
  2. import os

  3. def check(dir,text):
  4.   for i in os.listdir(dir):
  5.     if os.path.isdir(i): check(dir + "/" + i,text)
  6.     if re.search(r'.*\.txt',i):
  7.       file = open(dir + "/" + i,encoding="utf8").read()
  8.       print(str(i) + "\n" if re.search(text,file) else "",end="")

  9. check(os.getcwd(),"hello world")
复制代码
回复

使用道具 举报

0

主题

1

好友

61

积分

注册会员

Rank: 2

发表于 2016-2-16 15:25:26 |显示全部楼层

回帖奖励 +5

@crossing先生
请帮我看看,新手鼓起勇气努力写了大半天,期待前辈指点,有任何错误,不妥,都请您指出,拜谢
#!\usr\bin\python
#-*-encoding:utf-8-*-
#author=xuqq
#下面这个程序实现的功能是:在一个文件夹,包括子文件夹中,寻找包含相关内容的文件,把这些文件罗列出来
import os,re

def search_in_path(path_original,str_targit):
    targit_files = []
    if (os.path.exists(path_original) and os.path.isabs(path_original)):               
        for root,dir,files in os.walk(path_original):                                    #os.walk()遍历是个好东东
            print root
            print dir
            print files
            
            for file_obj in files:
                file_whole_name = os.path.join(root,file_obj)
                result = search_in_file(file_whole_name,str_targit)
                if result !="":
                    targit_files.append(result)
                else:
                    continue
    else:
        print "The path which you have input is not valid!"
    print "最终包括这个内容的文件有:\n"
    result_num = 0
    for tar in targit_files:
        print "%d\t%s" %(result_num,tar)
        result_num = result_num+1
            
def  search_in_file(file_original,str_targit):
    if os.path.isfile(file_original):
        fp = open(file_original,'r')
        match = False
        line = "file begin:"
        i = 1
        while line:
            line =  fp.readline()
            #print "以下打印内容:\n" ,line
            m = re.findall(str_targit,line)
            #print "m = \t",m
            if m !=[]:
                match =True
                print "在文件里找到了"
                break
            else:
                continue
            i = i+1
        print "%_%"*28
        print "match:\t",match
        if match ==True:
            print "Found it!\t"+file_original
            fp.close()
            print '*'*80
            return file_original
        else:
            print "Nothing found!"
            fp.close()
            print '#'*80
            return ""
            
def main():
    search_in_path("C:\Python27", "xuqq")
   
if __name__ =='__main__':
    main()
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2016-2-16 22:35:13 |显示全部楼层
xqqxjnt1988 发表于 2016-2-16 15:25
@crossing先生
请帮我看看,新手鼓起勇气努力写了大半天,期待前辈指点,有任何错误,不妥,都请您指出,拜 ...

查找文件里的内容不用readlines,直接read到一个字符串,然后find就可以了。
另外你这个代码好像无法检测子文件夹,因为你没有进一步对dir去递归搜索
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

0

主题

0

好友

26

积分

新手上路

Rank: 1

发表于 2017-1-22 09:03:09 |显示全部楼层
import os
def find_certain_files(keyword = input("search:") ):
    result = []
    for path,dirs,files in os.walk("文件夹"):
        for file in files:
            if file.endswith(".txt"):
                fileWithPath = os.path.join(path,file)
                a = open(fileWithPath)
                b = a.read()
                if keyword in b:
                    result.append(fileWithPath)
                a.close()

    print(result)
find_certain_files()
回复

使用道具 举报

1

主题

0

好友

45

积分

新手上路

Rank: 1

发表于 2017-3-7 15:43:42 |显示全部楼层
模仿上一个题目的一个解答编写的。让用户提供文件夹,文件类型和搜索文本。

#!/usr/bin/python
#This file is used to search files in path A. The names of the files contains B, and the content of the files contain C
#the input should like this:python search.py A B C

import os
import re
import sys

def searchmethod(path,filetype,text):
  all=[]
  for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
      f=file(os.path.join(dirpath,filename))
      content=f.read()
      f.close()
      #print content
      if os.path.splitext(filename)[1]==filetype and re.findall(text, content): # to match file type and file content
        all.append(os.path.join(dirpath,filename))
  print all

if __name__=='__main__':
  if len(sys.argv) !=4:
    print 'Please input like this:./9.py your_dir file_type your_match_string'
  elif os.path.exists(sys.argv[1]):
    searchmethod(sys.argv[1],sys.argv[2],sys.argv[3])
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-3-29 08:38 , Processed in 0.019942 second(s), 27 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部