import difflib import json import re from typing import List def compare_texts(text1: str, text2: str) -> str: """对比两段文本,返回差异""" lines1 = text1.splitlines(keepends=True) lines2 = text2.splitlines(keepends=True) diff = difflib.unified_diff(lines1, lines2, lineterm='') return ''.join(diff) def batch_replace(text: str, replacements: dict) -> str: """批量文本替换""" result = text for old, new in replacements.items(): result = result.replace(old, new) return result def format_json(json_str: str, indent: int = 2) -> str: """格式化JSON""" try: data = json.loads(json_str) return json.dumps(data, indent=indent, ensure_ascii=False) except json.JSONDecodeError as e: return f"JSON解析错误: {str(e)}" def minify_json(json_str: str) -> str: """压缩JSON""" try: data = json.loads(json_str) return json.dumps(data, separators=(',', ':'), ensure_ascii=False) except json.JSONDecodeError as e: return f"JSON解析错误: {str(e)}" def count_chars(text: str) -> dict: """统计字数""" total_chars = len(text) chinese_chars = len(re.findall(r'[一-鿿]', text)) english_chars = len(re.findall(r'[a-zA-Z]', text)) digits = len(re.findall(r'\d', text)) spaces = len(re.findall(r'\s', text)) punctuation = total_chars - chinese_chars - english_chars - digits - spaces return { '总字符数': total_chars, '中文字数': chinese_chars, '英文字母': english_chars, '数字': digits, '空格': spaces, '标点符号': punctuation, '总行数': len(text.splitlines()) }