Guest User

Untitled

a guest
Sep 22nd, 2024
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.51 KB | None | 0 0
  1. from dataclasses import dataclass, field
  2. from datetime import datetime
  3. from typing import List
  4. import os
  5. import hashlib
  6. import yaml
  7. import markdown
  8.  
  9. def compute_sha1(file_path: str) -> str:
  10.     """计算给定文件的SHA1哈希值"""
  11.     sha1 = hashlib.sha1()
  12.     with open(file_path, "rb") as f:
  13.         while chunk := f.read(8192):  # 逐块读取文件
  14.             sha1.update(chunk)
  15.     return sha1.hexdigest()
  16.  
  17. @dataclass
  18. class FileMetadata:
  19.     create_date: str = field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d %H:%M:%S"))  # 创建日期
  20.     edit_date: str = field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d %H:%M:%S"))    # 编辑日期
  21.     sha1sum: str = ""  # 文件的SHA1哈希值
  22.     filepath: str = ""  # 文件路径
  23.     tags: List[str] = field(default_factory=list)  # 标签列表
  24.     title: str = ""
  25.     def to_dict(self):
  26.         """将FileMetadata转换为字典,以便于JSON序列化"""
  27.         return {
  28.             "create_date": self.create_date,
  29.             "edit_date": self.edit_date,
  30.             "sha1sum": self.sha1sum,
  31.             "filepath": self.filepath,
  32.             "tags": self.tags,
  33.             "title": self.title
  34.         }
  35.  
  36.  
  37. def get_file_metadata(file_path: str, tags: List[str]) -> FileMetadata:
  38.     """获取文件的元数据,包括文件夹路径名作为标签"""
  39.     # 检查文件扩展名
  40.     _, file_extension = os.path.splitext(file_path)
  41.     allowed_extensions = ['.md']  # 允许的扩展名列表
  42.     if file_extension.lower() not in allowed_extensions:
  43.         raise ValueError(f"文件扩展名 '{file_extension}' 不被允许。请使用以下扩展名之一: {', '.join(allowed_extensions)}")
  44.  
  45.     # 获取文件的创建时间和修改时间
  46.     create_time = datetime.fromtimestamp(os.path.getctime(file_path)).strftime("%Y-%m-%d %H:%M")
  47.     edit_time = datetime.fromtimestamp(os.path.getmtime(file_path)).strftime("%Y-%m-%d %H:%M")
  48.  
  49.     # 计算文件的SHA1哈希值
  50.     sha1sum = compute_sha1(file_path)
  51.  
  52.     # 读取文件的第一行以获取标题
  53.     title = ""
  54.     with open(file_path, 'r', encoding='utf-8') as f:
  55.         first_line = f.readline().strip()
  56.         if first_line.startswith("# "):
  57.             title = first_line[2:].strip()  # 提取标题内容
  58.  
  59.  
  60.     # 创建FileMetadata实例
  61.     file_metadata = FileMetadata(
  62.         create_date=create_time,
  63.         edit_date=edit_time,
  64.         sha1sum=sha1sum,
  65.         filepath=file_path,
  66.         tags=tags,
  67.         title=title # 添加标题
  68.     )
  69.  
  70.     return file_metadata
  71. def process_files_in_directory(directory: str, tags: List[str]) -> List[FileMetadata]:
  72.     """处理指定目录中的所有文件并返回元数据"""
  73.     metadata_list = []
  74.     if os.path.isdir(directory):
  75.         for filename in os.listdir(directory):
  76.             file_path = os.path.join(directory, filename)
  77.             if os.path.isfile(file_path):  # 确保是文件
  78.                 try:
  79.                     file_metadata = get_file_metadata(file_path, tags)
  80.                     metadata_list.append(file_metadata)
  81.                    
  82.                 except:
  83.                     pass
  84.     else:
  85.         print(f"{directory} 不是一个有效的目录。")
  86.    
  87.     return metadata_list
  88.  
  89.  
  90.  
  91. # yaml
  92.  
  93. # read config
  94. # see blog_example.yaml
  95. def read_config(config_file: str) -> dict:
  96.     """读取 YAML 配置文件"""
  97.     with open(config_file, 'r') as file:
  98.         config = yaml.safe_load(file)
  99.     return config
  100.  
  101.  
  102. #  markdown
  103. def convert_md_to_html(md_file_path: str, output_html_path: str):
  104.     """将 Markdown 文件转换为 HTML 并保存"""
  105.     # 检查文件扩展名
  106.     _, file_extension = os.path.splitext(md_file_path)
  107.     if file_extension.lower() != '.md':
  108.         raise ValueError("提供的文件不是一个 Markdown 文件。请确保文件扩展名为 .md")
  109.  
  110.     # 读取 Markdown 文件内容
  111.     with open(md_file_path, 'r', encoding='utf-8') as md_file:
  112.         md_content = md_file.read()
  113.  
  114.     # 转换为 HTML
  115.     html_content = markdown.markdown(md_content)
  116.  
  117.     # 保存到 HTML 文件
  118.     with open(output_html_path, 'w', encoding='utf-8') as html_file:
  119.         html_file.write(html_content)
  120.  
  121.     print(f"已将 Markdown 文件 '{md_file_path}' 转换为 HTML 并保存为 '{output_html_path}'")
  122.  
  123. if __name__ == "__main__":
  124.    
  125.     # 使用示例
  126.     md_file_path = 'example.md'  # 输入 Markdown 文件路径
  127.     output_html_path = 'output.html'  # 输出 HTML 文件路径
  128.     convert_md_to_html(md_file_path, output_html_path)
  129.  
Advertisement
Add Comment
Please, Sign In to add comment