0

デスクトップのフォルダーから複数のテキスト ファイルを実行しようとしています。そこから olympic という単語を検索する必要があります。その 50 個のテキスト ファイルで olympic が見つかった場合は、 textfile1 = 2 textfile2 = 1 のように output.txt に保存する必要があります。 texfile=50 まで

import glob
import re
write_file = open("output.txt")
flist = glob.glob("./*.py")   # adjust glob pattern as desired
print flist
print " lines : path to file"
for fpath in flist:
    with open(fpath) as f: #open files
        lines = f.readlines()
        if (lines == 'olympic'):
            write_file.write("%s" % lines) #write the results
        print "%6d : %s" % (len(lines),fpath)
        #with open securely opens and closes the file
write_file.close() # close file

これは私がやろうとしていることですが、はい、エラーがいっぱいあることを知っています:)

複数のファイルを実行しようとしていますが、手動ではありません。ディレクトリ/フォルダー全体のファイルを自動的に実行し、それらの出力を 1 つのテキスト ファイルに保存する必要があります..'I have 50 text files and all files have word olympic , some have 1 some have 2/3 etc , i want to count the words from each text file and than save their output in one text file , like textfile1 = 2 , textfile2 = 3 etc in output.txt

4

2 に答える 2

0

そんな感じ:

fetch.py

#! /usr/bin/env python
import os
import sys


def get_counts(filepath, niddle):
    with open(filepath, 'rb') as f:
        return f.read().count(niddle)


if __name__ == '__main__':
    folder = sys.argv[1]
    niddle = sys.argv[2]
    assert os.path.isdir(folder), "Not a folder"
    output = open('results.txt', 'w')
    for dirpath, dirnames, filenames in os.walk(folder):
        for filename in filenames:
            if not filename.endswith('.html'): # or whatever
                continue
            filepath = os.path.abspath('%s/%s' % (dirpath, filename))
            result = '%s = %d' % (filepath, get_counts(filepath, niddle))
            output.write(result)
    output.close()

使用:

$ python fetch.py /path/to/search olimpic

于 2013-03-23T18:58:10.947 に答える
0

これを試して

import os
import re

filelist = [file for file in os.listdir('.') if '.py' in file]

for file in filelist:
  f = open(file,"r")
    lines = f.readlines()
    sum=0
    sum1=0
    for line in lines:
      if "olympics" in line:
        len(re.findall('\Wolympics\W', line))
        sum=sum+1
        print sum
      elif "Olympics" in line:
        sum1=sum1+1
        print sum1
    print "%6d : %s" % (len(line),file.name)
    f.close()

あなたが何をしようとしているのかよくわかりませんが、試してみました...

于 2013-03-23T17:12:13.010 に答える