Download utils/text_utils.py from PerrinT/office: direct link, hf CLI and curl.
- Browser
- Download file 1.71 kB
-
https://huggingface.co/spaces/PerrinT/office/resolve/main/utils/text_utils.py
- Command line
-
hf download hf://spaces/PerrinT/office/utils/text_utils.py
-
curl -L -o text_utils.py https://huggingface.co/spaces/PerrinT/office/resolve/main/utils/text_utils.py
1.71 kB
| 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()) | |
| } | |