Random String Generator with URL Extraction and Circumference Calculation

  • Share this:

Code introduction


This function generates a random string, extracts URLs from the given text, calculates the circumference of a circle with the given radius, saves the results to a JSON file, and returns the content of the file.


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

Code Type : Function

Code Difficulty : Intermediate


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

def generate_random_string(length):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

def extract_urls(text):
    url_regex = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.IGNORECASE)
    return url_regex.findall(text)

def calculate_circumference(radius):
    return 2 * math.pi * radius

def shuffle_list(input_list):
    shuffled_list = input_list[:]
    random.shuffle(shuffled_list)
    return shuffled_list

def save_to_file(data, filename):
    with open(filename, 'w') as file:
        json.dump(data, file)

def read_from_file(filename):
    with open(filename, 'r') as file:
        return json.load(file)

def xxx(arg1, arg2):
    random_string = generate_random_string(10)
    urls = extract_urls(arg1)
    circumference = calculate_circumference(arg2)
    shuffled_list = shuffle_list(urls)
    data = {
        "random_string": random_string,
        "urls": shuffled_list,
        "circumference": circumference
    }
    save_to_file(data, 'output.json')
    return read_from_file('output.json')