Random Sentence Generation and File Content Processing

  • Share this:

Code introduction


The function first generates a random sentence, then finds files with a specific pattern in the specified directory, reads the content of the files, converts the file content to JSON format, waits for 2 seconds, and finally shuffles the list of file contents.


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

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re
import json
import sys
import time
import random

def generate_random_sentence(length):
    words = ['the', 'and', 'to', 'of', 'a', 'in', 'for', 'is', 'on', 'that', 'by', 'this', 'with', 'i', 'you', 'it', 'not', 'or', 'be', 'are', 'from', 'at']
    sentence = ' '.join(random.choices(words, k=length))
    return sentence

def find_files(start_path, file_pattern):
    for root, dirs, files in os.walk(start_path):
        for file in files:
            if re.match(file_pattern, file):
                yield os.path.join(root, file)

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

def convert_string_to_json(input_string):
    try:
        return json.loads(input_string)
    except json.JSONDecodeError:
        return None

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

def randomize_list(input_list):
    random.shuffle(input_list)
    return input_list

def xxx(arg1, arg2):
    sentence = generate_random_sentence(10)
    files = find_files(arg1, arg2)
    file_contents = [read_file_content(file) for file in files]
    json_data = convert_string_to_json(file_contents[0])
    sleep_for_seconds(2)
    randomized_list = randomize_list(file_contents)
    return sentence, json_data, randomized_list                
              
Tags: