让 ai 写的 改了好几版 缩进处理有点麻烦 使用前先复制要处理的文本 用 quicker 打开文件可以一键执行 不想要窗口可以改后缀为.pyw 欢迎大佬改进或做成 js 代码或插件
代码
python
import re
import pyperclip
def convert_headings_to_list(text):
lines = text.splitlines()
result = []
counters = [0] * 6
last_level = 0
content_block = []
last_indent = 0
level_indents = {}
for line in lines:
heading_match = re.match(r'^(#{1,6})\s+(.+)$', line)
if heading_match:
# 处理之前累积的内容块
if content_block:
indent = " " * (last_level)
result.extend(indent + line for line in content_block)
content_block = []
level = len(heading_match.group(1))
content = heading_match.group(2)
# 重置更深层级的计数器
for i in range(level, 6):
counters[i] = 0
counters[level-1] += 1
# 计算新的缩进级别
if level in level_indents:
# 如果这个级别之前出现过,使用相同的缩进
new_indent = level_indents[level]
else:
# 如果是新的级别,计算合适的缩进
new_indent = level - 1
indent_diff = new_indent - last_indent
# 调整缩进差异
if abs(indent_diff) > 1:
if indent_diff > 0:
new_indent = last_indent + 1
else:
new_indent = last_indent - 1
# 记录这个级别的缩进
level_indents[level] = new_indent
# 应用缩进
indent = " " * new_indent
number = str(counters[level-1]) + "."
result.append(f"{indent}{number} {content}")
last_level = level
last_indent = new_indent
else:
# 收集非标题行到内容块
if line.strip():
content_block.append(line)
else:
if content_block:
indent = " " * last_level
result.extend(indent + line for line in content_block)
content_block = []
result.append(line)
# 处理最后的内容块
if content_block:
indent = " " * last_level
result.extend(indent + line for line in content_block)
return "\n".join(result)
def adjust_indentation(text):
lines = text.splitlines()
# 检查是否存在无缩进的行
has_zero_indent = any(not line.startswith(' ') and line.strip() for line in lines)
if not has_zero_indent:
# 找到最小缩进级别(最大标题级别)
min_indent = float('inf')
for line in lines:
if line.strip(): # 跳过空行
indent_count = len(line) - len(line.lstrip())
min_indent = min(min_indent, indent_count)
# 如果找到了缩进,从每行中删除对应数量的空格
if min_indent != float('inf'):
lines = [line[min_indent:] if line.strip() else line for line in lines]
return '\n'.join(lines)
# 获取剪贴板内容
clipboard_text = pyperclip.paste()
# 转换内容
converted_text = convert_headings_to_list(clipboard_text)
# 调整缩进
converted_text = adjust_indentation(converted_text)
# 写回剪贴板
pyperclip.copy(converted_text)
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于