Creating Directory, Generating Random String, and Extracting Numbers with Regex

  • Share this:

Code introduction


The function first creates a specified directory (if it does not exist), then generates a random string and a current time string, stores them in a JSON file, then extracts all numbers from the second argument using regular expressions, waits for 2 seconds, and returns the extracted numbers and current time.


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

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import datetime
import json
import os
import re
import sys
import time

def generate_random_string(length):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(length))

def xxx(arg1, arg2):
    # 创建一个目录
    os.makedirs(arg1, exist_ok=True)
    
    # 生成一个随机字符串
    random_string = generate_random_string(10)
    
    # 将当前时间转换为字符串
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # 将随机字符串和时间存储为JSON文件
    with open(os.path.join(arg1, random_string + '.json'), 'w') as json_file:
        json.dump({"time": current_time, "random_string": random_string}, json_file)
    
    # 使用正则表达式匹配字符串中的所有数字
    numbers = re.findall(r'\d+', arg2)
    
    # 等待2秒
    time.sleep(2)
    
    return numbers, current_time