OpenClaw 是一个开源的多功能工具库,以下是一个精简版的核心功能实现:

核心模块
"""
OpenClaw 精简版 - 多功能工具库
版本: 1.0.0 精简版
"""
class OpenClaw:
"""OpenClaw 核心类"""
def __init__(self, config=None):
"""
初始化 OpenClaw
参数:
config: 配置字典
"""
self.config = config or {}
self.modules = {}
self._init_core_modules()
def _init_core_modules(self):
"""初始化核心模块"""
self.modules = {
'file_processor': FileProcessor(),
'data_validator': DataValidator(),
'string_utils': StringUtils(),
'network_client': NetworkClient(),
'cache_manager': CacheManager()
}
def process_file(self, file_path, processor_type='default'):
"""
处理文件
参数:
file_path: 文件路径
processor_type: 处理器类型
"""
return self.modules['file_processor'].process(file_path, processor_type)
def validate_data(self, data, schema):
"""
验证数据
参数:
data: 待验证数据
schema: 验证模式
"""
return self.modules['data_validator'].validate(data, schema)
def string_transform(self, text, operation):
"""
字符串转换
参数:
text: 输入文本
operation: 转换操作
"""
return self.modules['string_utils'].transform(text, operation)
def make_request(self, url, method='GET', data=None):
"""
发起网络请求
参数:
url: 请求地址
method: 请求方法
data: 请求数据
"""
return self.modules['network_client'].request(url, method, data)
def cache_data(self, key, value, ttl=3600):
"""
缓存数据
参数:
key: 缓存键
value: 缓存值
ttl: 过期时间(秒)
"""
return self.modules['cache_manager'].set(key, value, ttl)
def get_cached_data(self, key):
"""
获取缓存数据
参数:
key: 缓存键
"""
return self.modules['cache_manager'].get(key)
class FileProcessor:
"""文件处理器"""
def __init__(self):
self.supported_formats = ['txt', 'json', 'csv', 'xml']
def process(self, file_path, processor_type='default'):
"""处理文件"""
import os
import json
import csv
if not os.path.exists(file_path):
raise FileNotFoundError(f"文件不存在: {file_path}")
file_ext = os.path.splitext(file_path)[1][1:].lower()
if processor_type == 'default':
return self._default_processor(file_path, file_ext)
elif processor_type == 'fast':
return self._fast_processor(file_path, file_ext)
else:
raise ValueError(f"不支持的处理器类型: {processor_type}")
def _default_processor(self, file_path, file_ext):
"""默认处理器"""
with open(file_path, 'r', encoding='utf-8') as f:
if file_ext == 'json':
return json.load(f)
elif file_ext == 'csv':
import csv
return list(csv.reader(f))
else:
return f.read()
def _fast_processor(self, file_path, file_ext):
"""快速处理器"""
import mmap
with open(file_path, 'r', encoding='utf-8') as f:
if file_ext == 'txt':
# 使用内存映射提高大文件读取性能
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
return mm.read().decode('utf-8')
else:
return self._default_processor(file_path, file_ext)
class DataValidator:
"""数据验证器"""
def validate(self, data, schema):
"""验证数据"""
if schema == 'email':
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, str(data)))
elif schema == 'phone':
import re
pattern = r'^1[3-9]\d{9}$' # 中国手机号
return bool(re.match(pattern, str(data)))
elif schema == 'required':
return data is not None and data != ''
elif schema == 'numeric':
return isinstance(data, (int, float, complex))
else:
raise ValueError(f"不支持的验证模式: {schema}")
class StringUtils:
"""字符串工具"""
def transform(self, text, operation):
"""字符串转换"""
operations = {
'upper': str.upper,
'lower': str.lower,
'title': str.title,
'reverse': lambda s: s[::-1],
'strip': str.strip,
'slugify': self._slugify
}
if operation not in operations:
raise ValueError(f"不支持的转换操作: {operation}")
return operations[operation](str(text))
def _slugify(self, text):
"""转换为URL友好的slug"""
import re
import unicodedata
# 转换为ASCII
text = unicodedata.normalize('NFKD', text)
text = text.encode('ascii', 'ignore').decode('ascii')
# 转换为小写,替换非字母数字字符为连字符
text = text.lower()
text = re.sub(r'[^a-z0-9]+', '-', text)
text = text.strip('-')
return text
class NetworkClient:
"""网络客户端"""
def __init__(self):
import requests
self.session = requests.Session()
self.timeout = 30
def request(self, url, method='GET', data=None, headers=None):
"""发起请求"""
import requests
method = method.upper()
headers = headers or {'User-Agent': 'OpenClaw/1.0'}
try:
if method == 'GET':
response = self.session.get(
url,
params=data,
headers=headers,
timeout=self.timeout
)
elif method == 'POST':
response = self.session.post(
url,
json=data,
headers=headers,
timeout=self.timeout
)
else:
raise ValueError(f"不支持的HTTP方法: {method}")
response.raise_for_status()
return response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text
except requests.exceptions.RequestException as e:
raise ConnectionError(f"网络请求失败: {str(e)}")
class CacheManager:
"""缓存管理器"""
def __init__(self):
self.cache = {}
import time
self.time = time
def set(self, key, value, ttl=3600):
"""设置缓存"""
expire_time = self.time.time() + ttl
self.cache[key] = {
'value': value,
'expire': expire_time
}
return True
def get(self, key):
"""获取缓存"""
if key not in self.cache:
return None
item = self.cache[key]
if self.time.time() > item['expire']:
del self.cache[key]
return None
return item['value']
def clear(self):
"""清空缓存"""
self.cache.clear()
return True
工具函数
# 工具函数模块
def create_openclaw_instance(config=None):
"""
创建OpenClaw实例的快捷函数
参数:
config: 配置字典
返回:
OpenClaw实例
"""
return OpenClaw(config)
def quick_validate_email(email):
"""
快速验证邮箱
参数:
email: 邮箱地址
返回:
验证结果
"""
validator = DataValidator()
return validator.validate(email, 'email')
def quick_download_file(url, save_path):
"""
快速下载文件
参数:
url: 文件URL
save_path: 保存路径
"""
import requests
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return True
except Exception as e:
raise Exception(f"文件下载失败: {str(e)}")
def format_file_size(size_bytes):
"""
格式化文件大小
参数:
size_bytes: 字节大小
返回:
格式化后的文件大小字符串
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size_bytes < 1024.0:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024.0
return f"{size_bytes:.2f} PB"
使用示例
# 使用示例
if __name__ == "__main__":
# 创建OpenClaw实例
claw = create_openclaw_instance({"debug": True})
# 示例1: 验证邮箱
email = "test@example.com"
is_valid = quick_validate_email(email)
print(f"邮箱验证结果: {email} -> {is_valid}")
# 示例2: 字符串转换
text = "Hello OpenClaw!"
result = claw.string_transform(text, "reverse")
print(f"字符串反转: {text} -> {result}")
# 示例3: 缓存数据
claw.cache_data("user:1001", {"name": "张三", "age": 25}, 300)
cached_user = claw.get_cached_data("user:1001")
print(f"缓存数据: {cached_user}")
# 示例4: 格式化文件大小
size = 1500000
formatted = format_file_size(size)
print(f"文件大小: {size} bytes -> {formatted}")
# 示例5: 数据验证
phone = "13800138000"
is_phone_valid = claw.validate_data(phone, "phone")
print(f"手机号验证: {phone} -> {is_phone_valid}")
配置文件示例
# config.yaml
openclaw:
version: "1.0.0"
debug: false
modules:
file_processor:
max_file_size: 104857600 # 100MB
encoding: "utf-8"
network_client:
timeout: 30
retry_count: 3
cache:
default_ttl: 3600
max_size: 1000
安装说明
# 最小依赖安装 pip install requests # 完整功能安装 pip install requests pyyaml
这个精简版OpenClaw包含了核心的文件处理、数据验证、字符串操作、网络请求和缓存管理功能,代码结构清晰,易于扩展和维护。
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。