Extract and Analyze File Numbers with Random String Output

  • Share this:

Code introduction


This function reads a specified file, extracts all numbers from the file, calculates their average, generates a random string, and then saves this information to a JSON file.


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

Code Type : Function

Code Difficulty : Intermediate


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

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

def xxx(arg1, arg2):
    # 读取文件内容
    with open(arg1, 'r') as file:
        content = file.read()

    # 使用正则表达式查找所有的数字
    numbers = re.findall(r'\d+', content)

    # 将数字转换为整数并计算平均值
    if numbers:
        average = sum(map(int, numbers)) / len(numbers)
    else:
        average = 0

    # 生成一个随机字符串
    random_str = generate_random_string()

    # 将结果写入JSON文件
    results = {
        "numbers": numbers,
        "average": average,
        "random_str": random_str
    }
    with open(arg2, 'w') as json_file:
        json.dump(results, json_file)

    return results