Code introduction
The function generates a random string, finds all .txt files in the current directory and returns their list of file paths, extracts all email addresses from the given text, counts the number of lines in each .txt file, and prints system information. Finally, it returns the generated random string, a list of email addresses, and a dictionary of file line counts.
Technology Stack : Generate random string, file traversal, regular expression matching, email extraction, file line count statistics, JSON formatted output, system information printing
Code Type : Function
Code Difficulty :
import os
import re
import sys
import json
import time
import random
import string
def generate_random_string(length=10):
return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
def find_files(directory, extension):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(extension):
yield os.path.join(root, file)
def extract_emails(text):
return re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
def count_lines_in_file(filename):
with open(filename, 'r') as file:
return sum(1 for _ in file)
def print_system_info():
info = {
'python_version': sys.version,
'os_name': os.name,
'platform': sys.platform,
'cpu_count': os.cpu_count()
}
print(json.dumps(info, indent=4))
def xxx(arg1, arg2):
random_str = generate_random_string(10)
files = list(find_files('.', '.txt'))
emails = extract_emails(arg1)
line_counts = {file: count_lines_in_file(file) for file in files}
print_system_info()
return random_str, emails, line_counts