【python】一些常用的小脚本

目录

找到指定后缀的文件列表

找到指定后缀的文件,返回找到的文件路径列表,会递归文件夹。

python 复制代码
import os



# 找到指定后缀的文件
def find_type(path:str,fix:str):
    dlist=os.listdir(path)
    file_list=[]
    for i in dlist:
        ps=os.path.join(path, i)
        if os.path.isdir(ps):
            file_list+=find_type(ps,fix)
        else:
            if(ps[-len(fix):]==fix):
                file_list.append(ps)
    return file_list

转换文件编码

示例为把gb2312编码的文件转化为utf8编码。

python 复制代码
def conv(file:str):
    s=""
    try:
        with open(file,encoding="gb2312") as f:
            s=f.read()
        os.remove(file)
        with open(file,mode="w+",encoding="utf-8") as f:
            f.write(s)
    except Exception as e:
        print("conv failed",file)

删除文件注释

输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。

例如C语言使用 // 和 /* */ 来注释,调用方式如下:

python 复制代码
del_comm("main.c","//",["/*","*/"])
python 复制代码
# 删除所有注释
def del_comm(file:str,line_comm:str,blok_comm:list[str]):
    text=""
    try:
        with open(file,encoding="utf-8") as f:
            lines=f.readlines()
    except Exception as e:
        print("decode failed",file)
        return
    for i in range(len(lines)):
        index=lines[i].find(line_comm)
        if(index>=0):
            lstr=lines[i][:index]
        else:
            lstr=lines[i].rstrip()
        if(len(lstr.strip())>0):
            text+=lstr+'\n'
        elif(text[-2:]=='\\\n'):
            text+='\n'
    index_start=0
    text_out=""
    while True:
        index=text.find(blok_comm[0],index_start)
        index_end=text.find(blok_comm[1],index)
        if(index>=0 and index_end>index):
            text_out+= text[index_start:index]
            index_start=index_end+len(blok_comm[1])
        else:
            text_out+=text[index_start:]
            break
    with open(file,mode="w+",encoding="utf-8") as f:
        f.write(text_out)
        

去除过多的空白字符

python 复制代码
def simplified(text:str):
  '''
  返回一个新字符串,去除过多的空白字符
  '''
  space=['\t', '\n', '\v', '\f', '\r',  ' ']

  r=""
  start=0
  is_empty=False
  while text[start] in space:
    start+=1
  for i in range(start,len(text)):
    if text[i] in space:
      is_empty=True
    else:
      if(is_empty==True):
        r+=" "
        is_empty=False
      r+=text[i]
  return r
相关推荐
2601_962293242 小时前
Python自动化统计团队工作量并生成可视化仪表盘的脚本方案【指导】
python·数据分析·自动化·可视化·仪表盘
点心的游戏开发世界2 小时前
GDScript 入门笔记(十一):Lambda 与匿名函数
开发语言·笔记·游戏引擎·godot
2601_962293793 小时前
OCRmyPDF批处理脚本:使用Python自动化复杂OCR任务
python·自动化·批处理脚本·ocrmypdf·ocr任务
事圆则缓4 小时前
Kotlin 协程完全指南
开发语言·kotlin
我爱写代码i5 小时前
BeLink - 支持生成多种URL 缩短网址PHP源码
开发语言·php·短网址php源码
Java后端的Ai之路5 小时前
20、Python - 备忘录模式
开发语言·人工智能·python·外观模式·备忘录模式
嘿嘿-665 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
2601_962077715 小时前
基于Python与NLP的新闻事件信息抽取实战:从NER到时空标准化
python·nlp·transformers·spacy·新闻事件抽取
JavaPub-rodert6 小时前
LangChain 从入门到 Agent 实战:用 Python 搭建一个真正能调用工具和知识库的 AI 助手
人工智能·python·langchain
统计学小王子6 小时前
数学建模国赛倒计时4天——《统计模型精讲(混合效应模型R语言实现)》
开发语言·数学建模·r语言