Форум сайта python.su
0
from pathlib import Path import glob from argparse import ArgumentParser def text_searcher(file, phrase): with open(file, encoding='utf8') as text: for num, line in enumerate(text, 1): if phrase in line: count = line.count(phrase) with open('report.txt', 'a+') as result: result.write(f'string number: {num} total count: {count}\n') return count if Path('report.txt').exists(): Path('report.txt').unlink() parser = ArgumentParser() parser.add_argument('directory', type=Path, help='Please enter directory') parser.add_argument('phrase', type=str, help='Please type phrase') args = parser.parse_args() files = glob.glob(f'{args.directory}/*.txt', recursive=True) sum = 0 for file in files: count = text_searcher(file, args.phrase) sum = sum + count with open('report.txt', 'a+') as total: total.write('-'*32 + '\n') total.write(f'Total: {sum}\n') print("Done!")
Офлайн
857
def text_searcher(file, phrase): total = 0 with open(file, encoding='utf8') as text: for num, line in enumerate(text, 1): if phrase in line: count = line.count(phrase) total += count with open('report.txt', 'a+') as result: result.write(f'string number: {num} total count: {count}\n') return total
Офлайн
0
py.user.nextОтлично! Все работает, проблема была после того как я писал одинаковое слово на следующей строке. Огромное Вам спасибо
Офлайн