视图模式选中按组合按键就可以对文本进行替换了
.ideavimrc
vmap <leader>cm :'<,'>!python D:\workspace\text.py minify<CR>
vmap <leader>ci :'<,'>!python D:\workspace\text.py where_in<CR>
vmap <leader>cv :'<,'>!python D:\workspace\text.py csv_to_sql_values<CR>
text.py
# !/usr/bin/env python3
import __main__ # 导入__main__模块,用于获取当前模块对象
import csv
import inspect
import re
import sys
from io import StringIO
def minify(text):
# 使用正则表达式将除了最后一个换行符外的所有换行符替换为空格
text = re.sub(r'\n(?=[^\n]*\n)', ' ', text)
# 多个空格替换成一个空格
# 找到引号中的文本并替换为占位符
placeholders = []
def replace_quotes(match):
placeholders.append(match.group(0))
return f'placeholder_{len(placeholders) - 1}'
processed_text = re.sub(r'(\'[^\']*\'|"[^"]*")', replace_quotes, text)
# 替换不在引号内的多个空格为一个空格
processed_text = re.sub(r' +', ' ', processed_text)
# 将占位符替换回原始的引号内文本
for i, placeholder in enumerate(placeholders):
processed_text = processed_text.replace(f'placeholder_{i}', placeholder)
return processed_text
def csv_to_sql_values(text):
# 使用StringIO将字符串转换为类文件对象
string_io = StringIO(text)
reader = csv.reader(string_io)
# 构建SQL插入语句的VALUES部分
sql_insert_values = []
for row in reader:
# 将每行数据转换为字符串,并使用括号包裹
values = ', '.join([f"'{value}'" for value in row])
sql_insert_values.append(f"({values})")
# 返回VALUES部分的字符串
return ',\n'.join(sql_insert_values)
def where_in(text):
# 使用正则表达式将除了最后一个换行符外的所有换行符替换为空格
text = re.sub(r'\n(?=[^\n]*\n)', "', '", text)
text = re.sub(r'^(.*)$', r"('\1')", text)
return text
# 获取当前所有函数
all_functions = [name for name, obj in inspect.getmembers(__main__) if inspect.isfunction(obj)]
def main():
if len(sys.argv) == 1:
sys.stdout.write(str(all_functions))
sys.stdout.flush()
return
# 从标准输入读取传递进来的文本
input_text = sys.stdin.read()
# 处理传递进来的文本
processed_text = process_text(input_text)
# 输出处理后的文本
sys.stdout.write(processed_text)
sys.stdout.flush()
def process_text(text):
for func_name in all_functions:
if sys.argv[1] == func_name:
func = globals().get(func_name)
return func(text)
return text
if __name__ == "__main__":
main()