悠悠楠杉
网站页面
```python
import re
from docx import Document
file, output
file): # 读取输入文件的内容 with open(inputfile, 'r', encoding='utf-8') as file:
content = file.read()
# 定义Markdown的标题、关键词、描述和正文模板
template = """
Title: {title}
Keywords: {keywords}
Description: {description}
{body}
"""
# 解析文章内容,分别提取标题、关键词、描述和正文
titlematch = re.search(r'^\w+:\s*(.*?)$', content, re.M)
if titlematch:
title = title_match.group(1).strip(':')
else:
title = "No Title"
keywords_match = re.search(r'^\w+:\s*(.*?),?\s*(.*?)$', content, re.M) # 假设关键词是两个词组,逗号分隔
if keywords_match:
keywords = keywords_match.group(1).strip(',') + ", " + keywords_match.group(2).strip(',')
else:
keywords = "No Keywords"
description_match = re.search(r'^\w+:\s*(.*?)$', content, re.M) # 假设描述紧接着关键词之后,也可能不直接跟在关键词后但存在此标记
if description_match:
description = description_match.group(1).strip(':')
else:
description = "No Description"
body = content[content.find('---'):].strip() # 提取从'---'之后的所有内容作为正文
body = body.replace('\n', '').replace('\r', '') # 移除多余的换行符和回车符,以符合Markdown格式要求
body = body if body else "No Body Content" # 如果没有正文内容,则显示提示信息
# 生成Markdown格式的文章并保存到输出文件
with open(output_file, 'w', encoding='utf-8') as file:
file.write(template.format(title=title, keywords=keywords, description=description, body=body))
print("Markdown文章已生成:", output_file)
print("标题:", title)
print("关键词:", keywords)
print("描述:", description)
print("正文(部分):", body[:100] + "..." if len(body) > 100 else body) # 仅显示前100个字符以节省空间,如果正文很长的话
input.txt', 'example
output.md') # exampleinput.txt是你想转换的文件,example_output.md是输出的Markdown文件。
```
这个脚本首先从example_output.md文件中。你可以根据需要调整正则表达式来适应不同的文章格式。