Word Count and Random String Generator

  • Share this:

Code introduction


This function takes three arguments: file path, length of random string, and output file path. The function first checks if the file exists, then counts the number of words in the file and generates a random string of specified length. Finally, the function writes the word count, random string, and the first 10 words from the file to the specified output file.


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

Code Type : File processing and string operations

Code Difficulty : Intermediate


                
                    
import os
import re
import json
import time
import math
import random
import string

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

def count_words_in_file(file_path):
    with open(file_path, 'r') as file:
        text = file.read().lower()
        words = re.findall(r'\b\w+\b', text)
        return len(words), words

def xxx(arg1, arg2, arg3):
    # arg1: file_path, arg2: length of random string, arg3: output file path
    if not os.path.exists(arg1):
        raise FileNotFoundError(f"The file {arg1} does not exist.")
    
    word_count, words = count_words_in_file(arg1)
    random_str = generate_random_string(arg2)
    
    with open(arg3, 'w') as output_file:
        output_file.write(f"Total words: {word_count}\n")
        output_file.write(f"Random string: {random_str}\n")
        for word in words[:10]:  # Display only the first 10 words
            output_file.write(f"{word}\n")