Python Code for Random String Generation, Time Retrieval, and Text Filtering

  • Share this:

Code introduction


The code includes functionalities for generating random strings, getting the current time, and filtering words in a text using a regular expression.


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

Code Type : String Manipulation

Code Difficulty : Advanced


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

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

def get_current_time():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def filter_words(text, pattern):
    return [word for word in text.split() if re.search(pattern, word)]

def main():
    random_string = generate_random_string(15)
    current_time = get_current_time()
    filtered_words = filter_words("Python is great for string manipulation", r'\w+')
    
    print(random_string)
    print(current_time)
    print(filtered_words)

data = {
    "type": "字符串处理",
    "hard": "中级",
    "explain": "该代码包含生成随机字符串、获取当前时间、按正则表达式过滤文本中的单词等功能。",
    "tench": "os, sys, json, re, random, string, time, datetime",
    "explain_en": "The code includes functionalities for generating random strings, getting the current time, and filtering words in a text using a regular expression.",
    "tench_en": "os, sys, json, re, random, string, time, datetime"
}

print(json.dumps(data, ensure_ascii=False, indent=4))