You can download this code by clicking the button below.
This code is now available for download.
This code block contains examples of using various built-in Python library functions, including generating random strings, finding files, counting occurrences of substrings, reading and writing files, removing duplicates from a list, sorting a list by length, reversing a string, and getting a random element from a list.
Technology Stack : os, re, json, random, string
Code Type : Code block
Code Difficulty : Intermediate
import os
import re
import json
import random
import string
def generate_random_string(length=10):
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def find_files(directory, extension):
return [os.path.join(dp, f) for dp, dn, filenames in os.walk(directory) for f in filenames if f.endswith(extension)]
def count_occurrences(text, substring):
return len(re.findall(re.escape(substring), text))
def read_file(file_path):
with open(file_path, 'r') as file:
return file.read()
def write_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
def remove_duplicates_from_list(input_list):
return list(set(input_list))
def sort_list_by_length(input_list):
return sorted(input_list, key=len)
def reverse_string(input_string):
return input_string[::-1]
def get_random_element_from_list(input_list):
return random.choice(input_list)
def main():
# Generate a random string
random_str = generate_random_string(15)
# Find all .txt files in the current directory
txt_files = find_files('.', '.txt')
# Count occurrences of "hello" in a sample text
sample_text = "hello world, hello again!"
count_hello = count_occurrences(sample_text, "hello")
# Read content from a file
file_content = read_file('sample.txt')
# Write content to a file
write_file('output.txt', 'This is a test file.')
# Remove duplicates from a list
duplicate_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = remove_duplicates_from_list(duplicate_list)
# Sort a list by length
string_list = ["apple", "banana", "cherry", "date"]
sorted_list = sort_list_by_length(string_list)
# Reverse a string
reversed_str = reverse_string("hello")
# Get a random element from a list
random_element = get_random_element_from_list(["apple", "banana", "cherry", "date"])
# Create a JSON object with the results
results = {
"random_str": random_str,
"txt_files": txt_files,
"count_hello": count_hello,
"file_content": file_content,
"unique_list": unique_list,
"sorted_list": sorted_list,
"reversed_str": reversed_str,
"random_element": random_element
}
# Write the JSON object to a file
write_file('results.json', json.dumps(results, indent=4))
if __name__ == "__main__":
main()