Random String Occurrence Counter in Files

  • Share this:

Code introduction


This function first generates a random string, then traverses all files with a specified extension in the specified directory, reads the file content, and counts the number of times the specified string appears in the file content. Finally, it prints out the total number of occurrences of the string.


Technology Stack : os, re, string, random, time

Code Type : Function

Code Difficulty : Advanced


                
                    
import os
import re
import time
import random
import string

def generate_random_string(length=10):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(length))

def find_files_with_extension(root_dir, extension):
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith(extension):
                yield os.path.join(root, file)

def read_file(file_path):
    with open(file_path, 'r') as file:
        return file.read()

def count_occurrences(text, substring):
    return len(re.findall(re.escape(substring), text))

def delay_execution(seconds):
    time.sleep(seconds)

def main():
    random_string = generate_random_string(15)
    root_directory = '/path/to/search'
    file_extension = '.txt'
    
    for file_path in find_files_with_extension(root_directory, file_extension):
        content = read_file(file_path)
        occurrences = count_occurrences(content, random_string)
        delay_execution(1)
    
    print(f"Occurrences of '{random_string}': {occurrences}")

def xxx(arg1, arg2):
    main()