首页 > 系统相关 >windows系统的code2md 和 md2code

windows系统的code2md 和 md2code

时间:2023-06-23 10:00:26浏览次数:32  
标签:index md windows code2md md2code file path root dir

code2md\code2md_v1.bat

@echo off
:start
set filePath=
set /p filePath=Please drag a file in the project(or project dir):
D:\Python38\python main.py  %filePath%
goto start

code2md\code2md_v1.py

import time
import os
import re
import sys

def get_millisecond():
    """
    :return: 获取精确毫秒时间戳,13位
    """
    return int(time.time())



 
def get_root_dir(dir_path):
    file_list = os.listdir(dir_path)
    path_list = []
    root_file_list = []
    for file in file_list:
        print(file)
        # 过滤隐藏文件
        if file.startswith('.'):
            continue
        # 过滤所有的文件
        is_file = re.findall(r'\.[^.\\/:*?"<>|\r\n]+$', file)
        if len(is_file):
            # 反向过滤,后缀文件
            res_abort = re.findall(re.compile(
                r'(\.json|d\.ts|config\.ts|config\.js)$'), file)
            if res_abort:
                continue
            # 保留根文件夹的(\.py|vue|js|ts)$ 结尾的文件
            res_save = re.findall(re.compile(r'(\.py|vue|js|ts|html)$'), file)
            if len(res_save):
                root_file_list.append(file)
            continue
        # 过滤node_modules
        res_abort = re.findall(re.compile(
            r'(__pycache__|venv|build|dist|node_modules|public|LICENSE)'), file)
        if len(res_abort):
            continue
        # 拼接成路径
        file_path = os.path.join(dir_path, file)
        path_list.append(file_path)
    return path_list, root_file_list
 
 
def get_deep_dirs(path):
    file_path = []
    for root, dirs, files in os.walk(path):
 
        # 过滤不符合的文件夹------------------------------------------------------------------------
        del_dir_index = []
        for i, dir in enumerate(dirs):
            # 过滤隐藏文件
            if dir.startswith('.'):
                del_dir_index.append(i)
            # 过滤掉所有不符合的文件夹
            res_abort = re.findall(re.compile(
                r'(__pycache__|venv|build|dist|node_modules|public|LICENSE|assets)'), dir)
            if len(res_abort):
                del_dir_index.append(i)
 
        # 去重,排序,过滤文件夹
        del_dir_index = list(set(del_dir_index))
        del_dir_index.sort()
        for counter, index in enumerate(del_dir_index):
            index = index - counter
            dirs.pop(index)
 
        # 过滤不符合的文件-----------------------------------------------------------------------------
        del_file_index = []
        for i, file in enumerate(files):
            # 过滤隐藏文件
            # (\.gitignore)|(\.prettierrc)
            if file.startswith('.'):
                del_file_index.append(i)
            # 过滤掉所有不符合的文件
            res_abort = re.findall(re.compile(
                r'(NOTE\.md|\.json|\.d\.ts|\.lock|\.config\.ts|\.config\.js|\.png|\.woff2|\.ttf|\.woff|\.css|README\.md|\.toml|swagger-ui-bundle.js)$'),
                file)
            if len(res_abort):
                del_file_index.append(i)
 
        # 去重排序,过滤文件
        del_file_index = list(set(del_file_index))
        del_file_index.sort()
        for counter, index in enumerate(del_file_index):
            index = index - counter
            files.pop(index)
 
        # 筛选所有符合后缀的文件------------------------------------------------------------------------
        for file in files:
            # 正向过滤含有(\.py|vue|js|ts)$ 结尾的文件
            res_save = re.findall(re.compile(r'(\.py|vue|js|ts|html)$'), file)
            if len(res_save):
                file_path.append(os.path.join(root, file))
    return file_path
 
 
def readcode_writemd(file_path, root_path,file_name):
    suffix = re.findall(r'\.[^.\\/:*?"<>|\r\n]+$', file_path)
    if len(suffix):
        suffix = suffix[0][1:]
    with open(file_path, "r", encoding='utf-8') as f:  # 打开文件
        head_line = f.readline()
        rest_line = f.read()
        write2md(head_line, head_line + rest_line,
                 suffix, file_path, root_path,file_name)
 
 
def write2md(head, content, suffix, file_path, root_path,file_name):
    with open(root_path + '/'+file_name, "a", encoding='utf-8') as f:  # 打开文件
        f.write(f"# `{file_path}`\n\n")
        # f.write(f"# {head}\n\n")
        f.write(f"```{suffix}\n")
        f.write(content)
        f.write(f"\n")
        f.write(f"```\n")
 
 
if __name__ == '__main__':
    if len(sys.argv) == 1:
        print('请随便拖进来一个文件夹里面的文件')
        exit(-1)
 
    file_path = sys.argv[1:][0]  # markdown路径
    root_path = os.path.dirname(file_path)
 
    file_name = 'z_'+str(get_millisecond())+'_NOTE.md'
    md_file = os.path.join(root_path, file_name)
 
    # 清楚上一次的文件
    if os.path.exists(md_file):
        os.remove(md_file)
 
    file_path_list = get_deep_dirs(root_path)
    for file_path in file_path_list:
        print(file_path)
        readcode_writemd(file_path, root_path,file_name)
    print('!!!complete!!!')
 


code2md\code2md_v2.bat

@echo off  
set filePath=
set /p filePath=Please drag a file in the project(or project dir):
D:\Python38\python F:\code2md\code2md_v2.py  %filePath%
ping 127.0.0.1 -n 5 > nul  
exit

code2md\code2md_v2.py

#!/usr/bin/env python3
import os
import subprocess
import re
import shutil
import sys
from pathlib import Path
from datetime import datetime
 
# 需要过滤的文件夹
exclude_dirs = ['__pycache__', 'venv', 'build', 'dist', 'node_modules', 'public', 'LICENSE', 'assets', 'vendor', 'tmp', 'static', 'templates']
# 需要过滤文件后缀
exclude_files = ['_NOTE.md', '.d.ts', '.lock', '.png', '.woff2', '.ttf', '.woff', '.css', 'README.md', '.toml', 'swagger-ui-bundle.js', '-lock.json']
# 需要保留的文件
include_exts = ['.py', '.vue', '.js', '.ts', '.html', '.go', '.mod', '.json','.txt','.sh','.command','.bat']
# 
md_suffix_table = {
    'command': 'sh',
}
 
 
def get_root_dir(dir_path):
    file_list = os.listdir(dir_path)
    path_list = []
    root_file_list = []
    for file in file_list:
        print(file)
        # 过滤隐藏文件
        if file.startswith('.'):
            continue
        # 过滤所有的文件
        is_file = re.findall(r'\.[^.\\/:*?"<>|\r\n]+$', file)
        if len(is_file):
            # 反向过滤,后缀文件
            res_abort = re.findall(re.compile(
                r'(d\.ts|config\.ts|-lock\.json)$'), file)
            if res_abort:
                continue
            # 保留根文件夹的(\.py|vue|js|ts)$ 结尾的文件
            res_save = re.findall(re.compile(r'(\.py|vue|config\.js|js|ts|html|txt|go|mod|json)$'), file)
            if len(res_save):
                root_file_list.append(file)
            continue
        # 过滤node_modules
        res_abort = re.findall(re.compile(
            r'(__pycache__|venv|build|dist|node_modules|public|LICENSE)'), file)
        if len(res_abort):
            continue
        # 拼接成路径
        file_path = os.path.join(dir_path, file)
        path_list.append(file_path)
    return path_list, root_file_list
 
 
def get_deep_dirs(path):
    file_path = []
    for root, dirs, files in os.walk(path):
        # 过滤不符合的文件夹------------------------------------------------------------------------
        del_dir_index = []
        for i, dir in enumerate(dirs):
            # 过滤隐藏文件
            if dir.startswith('.'):
                del_dir_index.append(i)
            # 过滤掉所有不符合的文件夹
            res_abort = re.findall(re.compile(
                r'(__pycache__|venv|build|dist|node_modules|public|LICENSE|assets|vendor|tmp|static|templates)'), dir)
            if len(res_abort):
                del_dir_index.append(i)
 
        # 去重,排序,过滤文件夹
        del_dir_index = list(set(del_dir_index))
        del_dir_index.sort()
        for counter, index in enumerate(del_dir_index):
            index = index - counter
            dirs.pop(index)
 
        # 过滤不符合的文件-----------------------------------------------------------------------------
        del_file_index = []
        for i, file in enumerate(files):
            # 过滤隐藏文件
            # (\.gitignore)|(\.prettierrc)
            if file.startswith('.'):
                del_file_index.append(i)
            # 过滤掉所有不符合的文件
            res_abort = re.findall(re.compile(
                r'(_NOTE\.md|\.d\.ts|\.lock|\.png|\.woff2|\.ttf|\.woff|\.css|README\.md|\.toml|swagger-ui-bundle.js|-lock\.json)$'),
                file)
            if len(res_abort):
                del_file_index.append(i)
 
        # 去重排序,过滤文件
        del_file_index = list(set(del_file_index))
        del_file_index.sort()
        for counter, index in enumerate(del_file_index):
            index = index - counter
            files.pop(index)
 
        # 筛选所有符合后缀的文件------------------------------------------------------------------------
        for file in files:
            # 正向过滤含有(\.py|vue|js|ts)$ 结尾的文件
            res_save = re.findall(re.compile(r'(\.py|vue|js|ts|html|go|mod|json)$'), file)
            if len(res_save):
                file_path.append(os.path.join(root, file))
    return file_path
 
def get_deep_dirs_fast(path):
    global exclude_dirs
    global exclude_files
    global include_exts
 
    
 
    file_path = []
    for root, dirs, files in os.walk(path):
        # 过滤不符合的文件夹------------------------------------------------------------------------
        dirs[:] = [d for d in dirs if not d.startswith('.') and not any(ex in d for ex in exclude_dirs)]
        # 过滤不符合的文件-----------------------------------------------------------------------------
        files[:] = [f for f in files if not f.startswith('.') and not any(ex in f for ex in exclude_files)]
        # 筛选所有符合后缀的文件------------------------------------------------------------------------
        for file in files:
            # 正向过滤含有(\.py|vue|js|ts)$ 结尾的文件
            if any(file.endswith(ext) for ext in include_exts):
                file_path.append(os.path.join(root, file))
    return file_path
 
 
 
def readcode_writemd(file_path,root_path ,md_file_path):
    suffix = re.findall(r'\.[^.\\/:*?"<>|\r\n]+$', file_path)
    if len(suffix):
        suffix = suffix[0][1:]
    with open(file_path, "r", encoding='utf-8') as f:  # 打开文件
        try:
            rest_line = f.read()
        except Exception as e:
            print(f'{file_path}文件编码读取错误,非utf-8')
            rest_line = '' 
        write2md(rest_line,suffix, file_path, root_path,md_file_path)
 
 
 
def get_md_title_path(file_path,root_path):
    # Get the common prefix of the two paths
    common_prefix = os.path.commonprefix([file_path, root_path])
    # Get the different parts of the two paths
    diff1 = file_path[len(common_prefix)+1:]
    # print(os.path.basename(root_path))
    # print(diff1)
    # print(os.path.join(os.path.basename(root_path),diff1))
    md_title = os.path.join(os.path.basename(root_path),diff1)
    return md_title
 
 
def get_code_md_lable_by_suffix(suffix):
    global md_suffix_table
 
    if md_suffix_table.get(suffix) is not None:
        return md_suffix_table.get(suffix)
 
    return suffix
 
 
def write2md(content, suffix, file_path,root_path, md_file_path):
    with open(md_file_path, "a", encoding='utf-8') as f:  # 打开文件
        md_title = get_md_title_path(file_path,root_path)
        f.write(f"# `{md_title}`\n\n")
        f.write(f"```{get_code_md_lable_by_suffix(suffix)}\n")
        f.write(content)
        f.write(f"\n")
        f.write(f"```\n\n\n")
 
 
 
def get_root_path(path):
    dir_path = path
    # 判断当前文件是否是文件
    if os.path.isfile(path):
        dir_path = os.path.dirname(path)
    return dir_path
 
 
 
def get_file_name():
    # Get the current time
    now = datetime.now()
    # Format the time as a string
    time_str = now.strftime('%Y-%m-%d_%H-%M-%S')
    # Create the file name
    file_name = f'Z_{time_str}_NOTE.md'
    return file_name
 
 
 
 
if __name__ == '__main__':
    root_path = get_root_path(sys.argv[1])
    md_file_name = get_file_name()
    md_file_path = os.path.join(root_path, md_file_name)
 
    file_path_list = get_deep_dirs_fast(root_path)
 
 
    for i,file_path in enumerate(file_path_list):
        print(i,'->',get_md_title_path(file_path,root_path))
        readcode_writemd(file_path, root_path,md_file_path)
 
    print('=============done=============')
 
    # os.system('open '+root_path)
 

code2md\md2code_v1.bat

@echo off  
set filePath=
set /p filePath=Please drag a md file:
D:\Python38\python F:\code2md\md2code_v1.py  %filePath%
ping 127.0.0.1 -n 5 > nul  
exit

code2md\md2code_v1.py

import os
import re
import sys
 
def create_from_file_path(base_dir,file_path,content):
    # Create the full directory path
    dir_path = os.path.join(base_dir, os.path.dirname(file_path))
    # Create the directories if they don't exist
    os.makedirs(dir_path, exist_ok=True)
    # Create the full file path
    full_file_path = os.path.join(base_dir, file_path)
    # Create the file
    with open(full_file_path,'w',encoding='utf-8') as f:
        f.write(content)
        f.close()
    
 
    
def get_root_path(path):
    dir_path = path
    # 判断当前文件是否是文件
    if os.path.isfile(path):
        dir_path = os.path.dirname(path)
    return dir_path
 
 
 
if __name__=="__main__":
    md_file_path = sys.argv[1]
    base_dir = get_root_path(md_file_path)
 
    with open(md_file_path, "r", encoding='utf-8') as f:  # 打开文件
        md_text = f.read()
        # Match the first-level headings and code blocks
        # \n{1,}# `(.+)`\n{1,}```\w{2,5}\n{1,}
        pattern = r'^# `(.+)`\n{1,}```(?:\w{2,}\n)([\s\S]+?)\n{1,}```\n{1,}'
        matches = re.findall(pattern, md_text, re.MULTILINE)
 
        # Loop over the matches
        for i, (file_path, code) in enumerate(matches):
            print(f"{i}->",file_path)
            create_from_file_path(base_dir,file_path,code)
        
        print(f'=============done_{len(matches)}=============')
        f.close()
        
 
 
 
 
 

标签:index,md,windows,code2md,md2code,file,path,root,dir
From: https://www.cnblogs.com/zhuoss/p/17498755.html

相关文章

  • Linux安装samba服务,实现与windows及其其他设备内网共享文件
    SMB协议其实是微软的一个文件共享协议,即Windows上的文件共享就是这个协议,samba是在Linux上对其的开源实现,由于历史悠久很多桌面和手机的文件共享客户端软件都支持这个协议,所以用来内网共享文件是比较合适的,但是由于安全性的原因,外网还是使用其他协议,如webdav.具体安装方法......
  • Windows域认证(笔记)
    Windows的认证包括三个部分:本地认证:用户直接操作计算机登录账户网络认证:远程连接到工作组中的某个设备域认证:登陆到域环境中的某个设备域内认证即采用了Kerberos协议的认证机制,与前两者相比最大的区别是有一个可信的第三方机构KDC的参与活动目录活动目录:ActiveDiret......
  • code2md md2code
    code2md/run_img2markdown.command#!/bin/bashsource/Users/song/Code/script_python/code2md/venv/bin/activate#echo-n'请任意拖入文件夹中的一个文件:'#readfile_pathpython3/Users/song/Code/script_python/code2md/main_img2markdown.pycode2md/main......
  • C:\Windows隐藏文件夹有哪些
    在Windows操作系统中,C:\Windows文件夹是一个重要的系统文件夹,用于存储操作系统的核心组件和文件。该文件夹通常包含许多隐藏文件和文件夹,这些文件和文件夹对于普通用户来说是不可见的。以下是一些常见的C:\Windows隐藏文件夹:C:\Windows\Temp:该文件夹用于存储临时文件,例如安装程序......
  • "Recent" 文件夹是一个特殊文件夹,在 Windows 操作系统中具有以下作用和功能:
    "Recent"文件夹是一个特殊文件夹,在Windows操作系统中具有以下作用和功能:最近使用的文件和文件夹:"Recent"文件夹会记录用户最近打开、编辑或访问过的文件和文件夹的快捷方式。这使得用户可以轻松地找到最近使用过的项目。快速访问文件:通过"Recent"文件夹,用户可以快速访问他......
  • C:\Windows\Installer\ 存储安装程序的数据库 修复和更改安装程序 安装程序的缓存
    C:\Windows\Installer\是一个特殊的系统文件夹,在Windows操作系统中扮演着重要的角色。它主要用于存储安装程序的相关信息和安装源。具体来说,C:\Windows\Installer\文件夹有以下几个作用和功能:存储安装程序的数据库:文件夹中包含一个名为"Installer"的数据库文件(即MSI数据库),......
  • C:\Windows\Inf\ 存储设备驱动程序信息 提供设备驱动程序安装和配置 存储硬件设备
    C:\Windows\Inf\是Windows操作系统中的一个文件夹,它在系统中起着重要的作用,并具有以下功能:存储设备驱动程序信息:C:\Windows\Inf\文件夹是Windows操作系统用于存储设备驱动程序信息的位置之一。当您在计算机上安装硬件设备时,相关的驱动程序文件会被复制到该文件夹中。这些文......
  • windows环境下,搭建RTSP视频推流服务器
    1.环境与配置1.1系统环境我这里使用的Windows1064位1.2下载RTSP服务器下载页面:https://github.com/aler9/rtsp-simple-server/releases这里,我们下载rtsp-simple-server_v0.19.1_windows_amd64.zip在百度网盘上下载也可以链接:https://pan.baidu.com/s/1FqMnAJWPo......
  • 手把手教你在Windows下搭建Vue开发环境
    一、下载Note.js下载地址:https://nodejs.org/zh-cn/download 二、点击安装包无脑下一步即可(建议修改下路径)三、在选择的安装路径下创建两个文件夹node_cache和node_global 四、打开CMD,设置缓存路径和全局模块存放路径4.1 缓存路径npmconfigsetcache"D:\So......
  • ubuntu 访问Windows的共享
    假定您的Windows共享网络连接已经正确设定好。网络主机的IP:192.168.0.1网络主机的使用者名称:myusername网络主机的登录密码:mypassword网络主机的登陆域为:mydomain分享中的目录名称:share1主机上要挂载的目录:/media/sharename要挂载网络共享目录时sudomkdir/medi......