Extract and Analyze Numbers in String with JSON and OS Integration

  • Share this:

Code introduction


This function uses regular expressions to extract numbers from a string, converts them to an integer list, and then uses the json module to convert the list to a JSON string. It calculates the difference between the maximum and minimum values in the list and uses the sys and os modules for output and getting the current working directory.


Technology Stack : re, json, math, sys, os

Code Type : Function

Code Difficulty : Intermediate


                
                    
import re
import json
import math
import sys
import os

def xxx(arg1, arg2):
    # 使用正则表达式匹配字符串中的数字
    pattern = re.compile(r'\d+')
    numbers = pattern.findall(arg1)
    
    # 将数字字符串转换为整数列表
    numbers = [int(num) for num in numbers]
    
    # 使用json模块将列表转换为JSON字符串
    json_str = json.dumps(numbers)
    
    # 使用math模块计算列表中最大值和最小值的差
    diff = max(numbers) - min(numbers)
    
    # 使用sys模块打印结果
    sys.stdout.write(f"Max: {max(numbers)}, Min: {min(numbers)}, Difference: {diff}\n")
    
    # 使用os模块获取当前工作目录
    current_directory = os.getcwd()
    
    # 将结果返回
    return json_str, current_directory                
              
Tags: