You can download this code by clicking the button below.
This code is now available for download.
This function generates a random string, gets the file size, reads the content of a file, replaces all occurrences in the text, sorts a list by length, generates a password, validates an email, gets a random item from a list, and checks if an object is serializable to JSON.
Technology Stack : os, re, string, random, json
Code Type : Function
Code Difficulty : Intermediate
import os
import re
import json
import random
import string
def generate_random_string(length):
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def extract_file_size(file_path):
if not os.path.exists(file_path):
return None
file_size = os.path.getsize(file_path)
return file_size
def read_file_content(file_path):
with open(file_path, 'r') as file:
content = file.read()
return content
def replace_all_occurrences(text, search, replace):
pattern = re.compile(search)
return pattern.sub(replace, text)
def sort_list_by_length(lst):
return sorted(lst, key=len)
def generate_password(length=8):
letters = string.ascii_letters + string.digits
return ''.join(random.choice(letters) for i in range(length))
def validate_email(email):
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
if re.match(pattern, email):
return True
else:
return False
def get_random_item_from_list(lst):
return random.choice(lst)
def json_serializable(obj):
try:
json.dumps(obj)
return True
except TypeError:
return False
def xxx(arg1, arg2):
random_string = generate_random_string(10)
file_size = extract_file_size(arg1)
content = read_file_content(arg2)
new_content = replace_all_occurrences(content, 'hello', 'world')
sorted_list = sort_list_by_length(['apple', 'orange', 'banana'])
password = generate_password(12)
is_valid_email = validate_email('example@example.com')
random_item = get_random_item_from_list(['apple', 'banana', 'cherry'])
is_json_serializable = json_serializable({'key': 'value'})
return {
'random_string': random_string,
'file_size': file_size,
'new_content': new_content,
'sorted_list': sorted_list,
'password': password,
'is_valid_email': is_valid_email,
'random_item': random_item,
'is_json_serializable': is_json_serializable
}
# JSON output