运行脚本
import sys
import subprocess
import os
import re
# 自动安装包的函数
def install_package(package):
try:
__import__(package)
except ImportError:
print(f"缺少包 {package},正在安装...")
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
print(f"{package} 安装完成。")
# 自动检查并安装 pandas
install_package("pandas")
import pandas as pd
def parse_text_file(input_path):
with open(input_path, 'r', encoding='utf-8') as f:
text = f.read()
pattern = re.compile(
r'\[(\d+)/\d+\] Generating: (.+?)\nGenerated chars: (\d+)\n\n([\s\S]+?)(?=\n\[\d+/\d+\] Generating:|\Z)',
re.MULTILINE
)
records = []
for match in pattern.finditer(text):
id_num = int(match.group(1))
category = match.group(2).strip()
generated_chars = int(match.group(3))
content = match.group(4).strip().replace('\n', ' ')
records.append({
"编号": id_num,
"分类": category,
"生成字符数": generated_chars,
"内容": content
})
df = pd.DataFrame(records)
return df
def main():
input_file = r'c:\1.txt' # 输入文件路径,修改为你的文件
base, _ = os.path.splitext(input_file)
output_file = base + '.csv' # 同目录同名csv文件
print("开始解析文本文件...")
df = parse_text_file(input_file)
print(f"解析完成,共 {len(df)} 条记录。")
print(f"保存为CSV文件:{output_file}")
df.to_csv(output_file, index=False, encoding='utf-8-sig')
print("完成!")
if __name__ == '__main__':
main()
原始内容 - 1.txt
[519/2028] Generating: 观点 - 科普 - 情感化
Generated chars: 454
In a world increasingly driven by technology, we must not forget the profound beauty of nature that surrounds us. The gentle rustle of leaves, the soft murmur of a stream, and the vibrant colors of a sunset remind us of life’s simple joys. Embracing these moments can rejuvenate our spirits, fostering a deeper connection to the planet. Let us prioritize this relationship, for in that connection lies not only our well-being but the future of our Earth.
[520/2028] Generating: 观点 - 科普 - 科普
Generated chars: 673
The pursuit of knowledge is a fundamental aspect of human nature, driving us to explore the mysteries of the universe. Science, with its methodical approach, serves as our primary tool for understanding the world. However, it's crucial to recognize that scientific literacy is not just for academics; it empowers everyone to make informed decisions. Embracing science in daily life fosters critical thinking and curiosity, enabling us to navigate complex issues like climate change and health. By integrating scientific principles into our everyday conversations, we not only elevate our understanding but also inspire future generations to question, explore, and innovate.
[521/2028] Generating: 观点 - 历史 - 正式
Generated chars: 455
The study of history is essential for understanding our present and shaping our future. It provides valuable insights into the complexities of human behavior, societal changes, and the consequences of actions taken by individuals and nations alike. By engaging with historical narratives, we cultivate critical thinking skills and foster a deeper appreciation for cultural diversity, ultimately guiding us toward more informed and responsible citizenship.
输出内容 1.csv
编号 | 分类 | 生成字符数 | 内容 |
---|---|---|---|
519 | 观点 - 科普 - 情感化 | 454 | In a world increasingly driven by technology, we must not forget the profound beauty of nature that surrounds us. The gentle rustle of leaves, the soft murmur of a stream, and the vibrant colors of a sunset remind us of life’s simple joys. Embracing these moments can rejuvenate our spirits, fostering a deeper connection to the planet. Let us prioritize this relationship, for in that connection lies not only our well-being but the future of our Earth. |
520 | 观点 - 科普 - 科普 | 673 | The pursuit of knowledge is a fundamental aspect of human nature, driving us to explore the mysteries of the universe. Science, with its methodical approach, serves as our primary tool for understanding the world. However, it's crucial to recognize that scientific literacy is not just for academics; it empowers everyone to make informed decisions. Embracing science in daily life fosters critical thinking and curiosity, enabling us to navigate complex issues like climate change and health. By integrating scientific principles into our everyday conversations, we not only elevate our understanding but also inspire future generations to question, explore, and innovate. |
521 | 观点 - 历史 - 正式 | 455 | The study of history is essential for understanding our present and shaping our future. It provides valuable insights into the complexities of human behavior, societal changes, and the consequences of actions taken by individuals and nations alike. By engaging with historical narratives, we cultivate critical thinking skills and foster a deeper appreciation for cultural diversity, ultimately guiding us toward more informed and responsible citizenship. |
❤️ 转载文章请注明出处,谢谢!❤️