1

特定の文字列についてユーザー指定のディレクトリ内のすべてのファイル (ファイル名とその内容の両方) を検索し、これらのファイルを新しいユーザー指定のディレクトリに移動できるプログラムを作成しようとしています。

編集:わかりましたので、コードにいくつかの変更を加えました。現在の動作方法は次のとおりです。ファイルのリストは os.path.walk() を使用して取得されます。次に、リスト内の各ファイルで、ユーザーが指定した文字列が検索されます。最初にファイル名のみが文字列についてチェックされ、肯定的な一致があれば別のリストに移動されます。次に、ファイル拡張子を使用して win32com.client 経由でファイルを開く方法を決定し、ファイルの内部を調べ始めます。最後に、元のリストに残っているファイルはプレーン テキスト ファイルと見なされ、それに応じて開かれ、検索されます。

ただし、何らかの理由で、プレーン テキスト ファイルのみがプログラムによって移動されます。誰かがこれがなぜなのかを理解できれば、それは大きな助けになるでしょう. :)

################
#Import required modules
import fileinput
from shutil import move
from os.path import abspath, join, splitext, split
from os import mkdir, walk, remove
import win32com.client

################
#Create lists to hold file names
file_list = list()
file_move_list = list()

#Define file extensions which need to be converted
excel_set = [".xls", ".xlsx", ".xlsm", ".xlsb"]
msword_set = [".doc", ".docx"]

################
#Define functions
def getFileList( searchdirectory ):
    #Get a list of all items in the directory to search
    for (dirpath, dirnames, filenames) in walk( searchdirectory ):
        for path in [ abspath( join( dirpath, filename ) ) for filename in filenames ]:
            file_list.append( path )

def searchFiles( readfilelist, movefilelist, searchstring ):
    #Get plain text from each file and search for searchstring
    for filename in readfilelist:
        ext = splitext( filename )[1]
        #Check filenames
        if searchstring in filename:
            movefilelist.append( filename )
            readfilelist.remove( filename )
        #Check if file is a pdf
        elif ext == ".pdf":
            content = getPDFContent( filename )
            if searchstring in content:
                movefilelist.append( filename )
        #Check if file is a word document
        elif ext in msword_set:
            app = win32com.client.Dispatch('Word.Application') 
            doc = app.Documents.Open( filename ) 
            if searchstring in doc.Content.Text:
                movefilelist.append( filename )
            app.Quit()
        #Check if file is an excel workbook/spreadsheet
        elif ext in excel_set:
            app = win32com.client.Dispatch( 'Excel.Application' )
            fileDir, fileName = split( filename )
            nameOnly = splitext( fileName )
            newName = nameOnly[0] + ".csv"
            outCSV = join( fileDir, newName )
            workbook = app.Workbooks.Open( filename )
            workbook.SaveAs(outCSV, FileFormat=24) # 24 is csv format
            workbook.Close(False)
            for line in open( outCSV, mode='r' ):
                if searchstring in line:
                    movefilelist.append( filename )
            app.Quit()
            remove( outCSV )
        #Assume all other files are plain text
        else:
            for line in open( filename, mode='r' ):
                if searchstring in line:
                    movefilelist.append( filename )
        readfilelist.remove( filename )

def moveFiles( movelist, destinationdirectory ):
    mkdir( destinationdirectory )
    for path in movelist:
        #Move the files to the destination folder
        move( path, destinationdirectory )
    print( 'Done' )

def getPDFContent( filename ):
    content = ""
    pdf = pyPdf.PdfFileReader( file( filename, "rb" ) )
    # Extract text from each page and add to content
    for i in range( 0, pdf.getNumPages() ):
        content += pdf.getPage(i).extractText() + " \n"
    return content

################
#Run as main
if __name__=='__main__':
    search_directory = input( 'Enter the path of the directory you wish to search through: ' )
    search_string = input( 'Enter the search term: ' )
    destination_directory = input( 'Enter the name of the new directory which will contain the moved files: ' )
    getFileList( search_directory )
    searchFiles( file_list, file_move_list, search_string )
    moveFiles( file_move_list, destination_directory )

これについて私が得ることができる助けは大歓迎です。(参考までに、私はPython 3.2.1を使用しています)

4

4 に答える 4

0

pdf、xls などはラスター形式またはベクター形式であるため、最初に変換する必要があるため、検索するテキストはありません。それらを変換して出力を検索できる pdtotext などのツールがあります。

于 2011-07-11T19:59:19.587 に答える
0

ウィンドウの場合、これを考慮してください:

os.system('findstr /C:"text to search for" *.*')

これは、あなたが望むすべてをほとんど行います。

于 2011-07-11T16:28:18.543 に答える
0

grinライブラリ ( source )の使用を検討してください。コンソール スクリプトとしても、ビルドできるライブラリとしても使用できます。バイナリ ファイルの検出がサポートされています。

于 2011-07-11T18:30:09.793 に答える