Python读取显示Latex的公式文档,Python加载显示markdown文件。

news2025/3/13 8:25:51

平时用LLM大语言模型去解释文献里面的公式含义直接复制的格式word看不懂,基于这个web可以正常加载显示。在这里插入图片描述
下面是读取的效果展示:在这里插入图片描述下面程序保存为stl_read.py然后运行下面指令。

streamlit run  stl_read.py
import streamlit as st
import base64
import re
from pathlib import Path
import pandas as pd
from streamlit_ace import st_ace

# 设置页面配置
st.set_page_config(
    page_title="公式文档查看器",
    page_icon="📝",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 自定义CSS样式
st.markdown("""
<style>
    .main {
        background-color: #f8f9fa;
    }
    .stApp {
        max-width: 1200px;
        margin: 0 auto;
    }
    h1, h2, h3 {
        color: #2c3e50;
    }
    .css-18e3th9 {
        padding-top: 2rem;
    }
    .stMarkdown {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    code {
        background-color: #f0f2f5;
        padding: 0.2em 0.4em;
        border-radius: 3px;
    }
    pre code {
        display: block;
        padding: 1em;
        overflow-x: auto;
        line-height: 1.45;
    }
    blockquote {
        border-left: 4px solid #6c757d;
        padding-left: 1em;
        color: #6c757d;
        margin-left: 0;
    }
    hr {
        border: none;
        height: 1px;
        background-color: #e1e4e8;
        margin: 2em 0;
    }
    table {
        border-collapse: collapse;
        width: 100%;
        margin: 1em 0;
    }
    th, td {
        border: 1px solid #e1e4e8;
        padding: 0.6em 1em;
    }
    th {
        background-color: #f0f2f5;
        font-weight: 600;
    }
    img {
        max-width: 100%;
        height: auto;
        display: block;
        margin: 1em 0;
    }
    .katex {
        font-size: 1.1em;
    }
    .uploaded-file-info {
        background-color: #e8f4f8;
        padding: 1rem;
        border-radius: 5px;
        margin-bottom: 1rem;
        border-left: 5px solid #4a86e8;
    }
    .editor-container {
        border: 1px solid #ddd;
        border-radius: 5px;
        margin-bottom: 1rem;
    }
    .section-title {
        font-size: 1.2rem;
        font-weight: 600;
        margin-bottom: 0.5rem;
        color: #2c3e50;
    }
    .info-card {
        background-color: white;
        padding: 1.5rem;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        margin-bottom: 1rem;
    }
    /* 隐藏 Streamlit 默认的菜单按钮和部署按钮 */
    #MainMenu {visibility: hidden;}
    .stDeployButton {display: none;}
    header {visibility: hidden;}
    footer {visibility: hidden;}
    .block-container {padding-top: 2rem;}
</style>
""", unsafe_allow_html=True)


# 处理Markdown中的LaTeX公式
def process_latex(content):
    """
    处理LaTeX公式以便在Streamlit中正确渲染

    增强版函数,支持处理不同格式和位置的LaTeX公式
    """
    # 处理1: 将 \[ 和 \] 之间的公式替换为 $$ 和 $$ (显示公式)
    content = re.sub(r'\\\[(.*?)\\\]', r'$$\1$$', content, flags=re.DOTALL)

    # 处理2: 将 \begin{equation} 和 \end{equation} 之间的公式替换为 $$ 和 $$
    content = re.sub(r'\\begin\{equation\}(.*?)\\end\{equation\}', r'$$\1$$', content, flags=re.DOTALL)

    # 处理3: 将 \begin{align} 和 \end{align} 之间的公式替换为 $$ 和 $$
    content = re.sub(r'\\begin\{align\}(.*?)\\end\{align\}', r'$$\1$$', content, flags=re.DOTALL)

    # 处理4: 将文本中的 \( 和 \) 之间的公式替换为 $ 和 $ (内联公式)
    content = re.sub(r'\\\((.*?)\\\)', r'$\1$', content, flags=re.DOTALL)

    # 处理5: 将文本中的 \frac、\partial 等LaTeX命令包装成内联公式
    # 正则表达式匹配 \命令{参数} 格式但不在已有的 $ 或 $$ 中
    def wrap_standalone_latex_cmd(match):
        # 如果前后已经有 $ 或 $$,则不处理
        if re.search(r'(\$|\$\$)[^\$]*' + re.escape(match.group(0)) + r'[^\$]*(\$|\$\$)', content):
            return match.group(0)
        return f"${match.group(0)}$"

    # 匹配常见的LaTeX命令:
    latex_cmd_pattern = r'\\(frac|partial|sum|int|prod|sqrt|alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega|infty|cdot|times|div|geq|leq|neq|approx|sim|pm|mp|in|subset|supset|cup|cap|rightarrow|leftarrow|Rightarrow|Leftarrow|mathbb|mathbf|mathcal|mathrm|text|hat|bar|dot|ddot|vec|overrightarrow|underline|overline|widehat|widetilde|overbrace|underbrace){1}(\{[^{}]*\}|\^[^{}]*|\_{1}[^{}]*)'

    # 尝试匹配单独的LaTeX命令,并用$包裹
    content = re.sub(latex_cmd_pattern, wrap_standalone_latex_cmd, content)

    # 处理6: 特殊处理 (\frac{...}{...}) 的情况
    # 匹配格式如 (\frac{a}{b}) 并替换为 ($\frac{a}{b}$)
    content = re.sub(r'\(\\(frac|partial|sum|int)(\{[^{}]*\})(\{[^{}]*\})\)', r'($\\\1\2\3$)', content)

    return content


# 获取文件元数据
def get_file_metadata(file):
    return {
        "filename": file.name,
        "size": f"{file.size / 1024:.2f} KB",
        "type": file.type
    }


# 显示带有动画的标题
st.markdown("""
<div style="text-align: center; margin-bottom: 2rem;">
    <h1 style="color: #4a86e8; font-size: 2.5rem; margin-bottom: 0.5rem;">公式文档查看器</h1>
    <p style="color: #6c757d; font-size: 1.1rem;">查看和编辑公式文档,支持各种公式</p>
</div>
""", unsafe_allow_html=True)

# 创建侧边栏
with st.sidebar:
    st.markdown("## 📋 控制面板")

    # 文件上传组件
    uploaded_file = st.file_uploader("上传公式文档", type=["md", "txt"],
                                     help="上传包含公式的文档")

    st.markdown("---")
    st.markdown("## ⚙️ 显示设置")

    # 显示设置
    show_raw = st.checkbox("显示原始内容", value=False)
    enable_editor = st.checkbox("启用编辑器", value=False)  # 默认不选中

    # 主题选择
    theme = st.selectbox("颜色主题",
                         ["亮色", "暗色", "蓝色", "绿色", "紫色"],
                         index=0)

    # 应用主题
    if theme == "暗色":
        st.markdown("""
        <style>
            .main { background-color: #1e1e1e; color: #e0e0e0; }
            h1, h2, h3 { color: #e0e0e0; }
            .info-card { background-color: #2d2d2d; color: #e0e0e0; }
            code { background-color: #333; color: #e0e0e0; }
            th { background-color: #333; }
            th, td { border-color: #444; }
            .uploaded-file-info { background-color: #2d2d2d; border-left-color: #4a86e8; }
        </style>
        """, unsafe_allow_html=True)
    elif theme == "蓝色":
        st.markdown("""
        <style>
            .main { background-color: #f0f4f8; }
            h1, h2, h3 { color: #1a5276; }
            .info-card { background-color: white; border-left: 5px solid #2980b9; }
            .uploaded-file-info { border-left-color: #2980b9; background-color: #ebf5fb; }
        </style>
        """, unsafe_allow_html=True)
    elif theme == "绿色":
        st.markdown("""
        <style>
            .main { background-color: #f0f8f4; }
            h1, h2, h3 { color: #1e8449; }
            .info-card { background-color: white; border-left: 5px solid #27ae60; }
            .uploaded-file-info { border-left-color: #27ae60; background-color: #ebfaf0; }
        </style>
        """, unsafe_allow_html=True)
    elif theme == "紫色":
        st.markdown("""
        <style>
            .main { background-color: #f5f0f8; }
            h1, h2, h3 { color: #6c3483; }
            .info-card { background-color: white; border-left: 5px solid #8e44ad; }
            .uploaded-file-info { border-left-color: #8e44ad; background-color: #f4ecf7; }
        </style>
        """, unsafe_allow_html=True)

    st.markdown("---")
    st.markdown("""

    """)

# 主要内容
if uploaded_file is not None:
    try:
        # 读取文件
        content = uploaded_file.getvalue().decode("utf-8")

        # 处理LaTeX公式以便正确渲染
        processed_content = process_latex(content)

        # 获取元数据
        metadata = get_file_metadata(uploaded_file)

        # 在精美的卡片中显示文件信息
        st.markdown(f"""
        <div class="uploaded-file-info">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <h3 style="margin: 0;">📄 {metadata['filename']}</h3>
                    <p style="margin: 0.5rem 0 0 0;">大小: {metadata['size']} | 类型: {metadata['type']}</p>
                </div>
                <div style="text-align: right;">
                    <p style="margin: 0;">上传时间: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
                </div>
            </div>
        </div>
        """, unsafe_allow_html=True)

        # 可选的原始内容显示
        if show_raw:
            st.markdown("### 原始内容")
            st.code(content, language="markdown")
            st.markdown("---")

        # 编辑器(如果启用)
        if enable_editor:
            st.markdown('<p class="section-title">📝 编辑器</p>', unsafe_allow_html=True)
            st.markdown('<div class="editor-container">', unsafe_allow_html=True)
            edited_content = st_ace(
                value=content,
                language="markdown",
                theme="github" if theme == "亮色" else "monokai",
                height=300,
                auto_update=True
            )
            st.markdown('</div>', unsafe_allow_html=True)

            # 使用编辑后的内容进行渲染
            processed_content = process_latex(edited_content)

        # 渲染处理后的markdown内容
        st.markdown('<div class="info-card">', unsafe_allow_html=True)
        st.markdown("### 渲染内容")
        st.markdown(processed_content)
        st.markdown('</div>', unsafe_allow_html=True)

    except Exception as e:
        st.error(f"处理文件时出错: {str(e)}")

else:
    # 当没有上传文件时显示欢迎信息和说明
    st.markdown("""
    <div class="info-card" style="text-align: center;">
        <h2>欢迎使用公式文档查看器</h2>
        <p>上传一个公式文档开始使用</p>
        <div style="margin: 2rem 0;">
            <svg width="100" height="100" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M13 12H21.5L12.5 3L3.5 12H12V21H13V12Z" fill="#4a86e8"/>
            </svg>
        </div>
        <p>支持各种格式的公式,可以提供完美显示体验。</p>
    </div>
    """, unsafe_allow_html=True)

    # 功能卡片
    col1, col2, col3 = st.columns(3)

    with col1:
        st.markdown("""
        <div class="info-card" style="height: 200px;">
            <h3 style="color: #4a86e8;">📐 全面支持</h3>
            <p>支持内联公式和显示公式,自动识别公式命令和环境。</p>
        </div>
        """, unsafe_allow_html=True)

    with col2:
        st.markdown("""
        <div class="info-card" style="height: 200px;">
            <h3 style="color: #4a86e8;">🎨 多种主题</h3>
            <p>提供亮色、暗色和彩色主题,满足不同的阅读偏好。</p>
        </div>
        """, unsafe_allow_html=True)

    with col3:
        st.markdown("""
        <div class="info-card" style="height: 200px;">
            <h3 style="color: #4a86e8;">✏️ 内置编辑器</h3>
            <p>编辑和实时预览文档,方便调整和修改内容。</p>
        </div>
        """, unsafe_allow_html=True)

# 页脚
st.markdown("""
<div style="text-align: center; margin-top: 3rem; padding: 1rem; border-top: 1px solid #ddd;">
    <p style="color: #6c757d;">公式文档查看器 © 2025</p>
</div>
""", unsafe_allow_html=True)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2314194.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

mapbox高阶,结合threejs(threebox)添加extrusion挤出几何体,并添加侧面窗户贴图和楼顶贴图

👨‍⚕️ 主页: gis分享者 👨‍⚕️ 感谢各位大佬 点赞👍 收藏⭐ 留言📝 加关注✅! 👨‍⚕️ 收录于专栏:mapbox 从入门到精通 文章目录 一、🍀前言1.1 ☘️mapboxgl.Map 地图对象1.2 ☘️mapboxgl.Map style属性1.3 ☘️threebox extrusion挤出几何体二、🍀…

mock的定义和使用场景

Python自动化中使用mock的示例 在Python自动化测试中&#xff0c;mock 用于模拟对象、函数或方法的行为&#xff0c;以便在隔离的环境中测试代码。以下是一个简单的示例&#xff1a; 假设你有一个 user.py 模块&#xff0c;其中包含一个 get_user_info 函数&#xff0c;用于从…

封装Axios拦截器实现用户无感刷新AccessToken实践指南

一、背景与需求场景 1.1 单点登录体系中的Token管理 在单点登录&#xff08;SSO&#xff09;体系下&#xff0c;用户登录后系统会颁发两种令牌&#xff1a; AccessToken&#xff1a;短期有效&#xff08;2小时&#xff09;&#xff0c;用于接口鉴权 RefreshToken&#xff1a…

CSDN博客:Markdown编辑语法教程总结教程(下)

❤个人主页&#xff1a;折枝寄北的博客 Markdown编辑语法教程总结 前言1. LaTex数学公式2. 插入不同类别的图2.1 插入甘特图2.2 插入UML图2.3 插入Mermaid流程图2.4 插入Flowchart流程图2.5 插入classDiagram类图 3. CSDN快捷键4. 字体相关设置4.1 字体样式改变4.2 字体大小改变…

【Python】06、流程控制语句

文章目录 1.条件判断语句1.1 if 语句2. input 函数3.if-else 语句4.if-elif-else 语句 2.循环语句2.1 while语句2.2 while语句练习&#xff1a;2.3 循环嵌套2.4 break和continue 通过流程控制语句&#xff0c;可以改变程序的执行顺序&#xff0c;也可以让指定程序反复执行多次。…

《python》—— threading库(线程和多线程)

文章目录 threading简介threading基本概念常用类和方法线程同步线程池实例 threading简介 threading 是 Python 标准库中用于实现多线程编程的模块。多线程编程允许程序同时执行多个任务&#xff0c;提高程序的并发性能&#xff0c;尤其适用于 I/O 密集型任务&#xff0c;例如…

【数据分享】2000-2024年全国逐年归一化植被指数(NDVI)栅格数据(年最大值)

NDVI&#xff0c;全名为Normalized Difference Vegetation Index&#xff0c;中文名称为归一化植被指数。这个指数可以用来定性和定量评价植被覆盖及其生长活力&#xff0c;我们也可以简单地将它理解为体现植被密度和健康状况的一个指标。 之前我们给大家分享了来源于MOD13A3数…

混沌理论与混沌映射——算法改进初始化创新点之一

混沌理论与混沌映射 混沌理论研究混沌系统的动力学&#xff0c;其特征是非线性和对初始条件的极端敏感性。即使在这些条件下的微小变化也可能导致系统结果的显著变化。尽管看起来是随机的&#xff0c;混沌系统可以在不依赖随机性的情况下表现出不规则的行为&#xff0c;因为确…

19874并查集

19874并查集 ⭐️难度&#xff1a;中等 &#x1f31f;考点&#xff1a;并查集、数据结构 &#x1f4d6; &#x1f4da; import java.util.*;public class Main {static int N 100010;static int[] a new int[N];static int[] p new int[N];static int n;static int m;st…

Jmeter下载安装配置及使用

1、下载 官网地址&#xff1a;Apache JMeter - Download Apache JMeter 2、配置环境变量 ①找到环境变量&#xff0c;两种方法 法一&#xff1a;我的电脑→右键菜单→属性→高级系统设置→环境变量 法二&#xff1a;直接搜索环境变量 ②新建两个系统变量 1.变量名&#x…

【从零开始学习计算机科学】编译原理(一)编译过程概述

【从零开始学习计算机科学】编译原理(一)编译过程概述 绪论编译过程概述词法分析语法分析代码优化代码生成其他功能编译器的前端和后端绪论 什么叫编译程序?为什么我们需要编译程序?编译程序就是一个程序,将便于人编写、阅读、维护的高级计算机语言所写作的源代码程序,翻…

【算法day8】 Z 字形变换 -O(n)算法思路整理

Z 字形变换&#xff0c;算法思路整理 https://leetcode.cn/problems/zigzag-conversion/description/ 将一个给定字符串 s 根据给定的行数 numRows &#xff0c;以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 “PAYPALISHIRING” 行数为 3 时&#xff0c;排列如下…

L3-1 夺宝大赛

输入样例 1&#xff1a; 5 7 1 1 1 1 1 0 1 1 1 1 1 1 0 0 1 1 0 2 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 7 1 5 7 1 1 1 5 5 3 1 3 5 1 4输出样例 1&#xff1a; 7 6样例 1 说明&#xff1a; 七支队伍到达大本营的时间顺次为&#xff1a;7、不可能、5、3、3、5、6&#xff0c…

Matlab:矩阵运算篇——矩阵

目录 1.定义 实例——创建矩阵 实例——创建复数矩阵 2.矩阵的生成 实例——M文件矩阵 2.利用文本创建 实例——创建生活用品矩阵 3.创建特殊矩阵 实例——生成特殊矩阵 4.矩阵元素的运算 1.矩阵元素的修改 实例——新矩阵的生成 2.矩阵的变维 实例——矩阵维度修…

泛微ecode的页面开发发送请求参数携带集合

1.在开发过程中我们难免遇见会存在需要将集合传递到后端的情况&#xff0c;那么这里就有一些如下的注意事项&#xff0c;如以下代码&#xff1a; // 新增action.boundasync addQuestion(formData) {var theList this.questionAnswerList;var questionAnswerListArray new Ar…

Javaweb后端全局异常处理器

类名随便定义 这是异常处理的方法exceptionhandler responsebody作用&#xff0c;方法的响应值返回给前端&#xff0c;如果返回的是集合对象&#xff0c;会把集合对象转为json&#xff0c;再给前端响应返回

SpringBoot缓存抽象:@Cacheable与缓存管理器配置

文章目录 引言一、SpringBoot缓存抽象概述二、Cacheable注解详解2.1 Cacheable的关键属性 三、缓存管理器配置四、自定义键生成策略五、缓存同步与失效策略六、SpringBoot缓存最佳实践总结 引言 缓存是提升应用性能的关键技术&#xff0c;SpringBoot提供了强大的缓存抽象层&am…

江科大51单片机笔记【11】AT24C02(I2C总线)

一、存储器 1.介绍 RAM的特点是存储速度特别快&#xff0c;但是掉电会丢失&#xff1b;ROM的特点是存储速度特别慢&#xff0c;但是掉电不会丢失 SRAM是所有存储器最快的&#xff0c;一般用于电脑的CPU高速缓存&#xff0c;容量相对较少&#xff0c;成本较高&#xff1b;DRAM…

外层元素旋转,其包括在内的子元素一并旋转(不改变旋转中心),单元测试

思路&#xff1a;外层旋转后坐标&#xff0c;元素旋转后坐标&#xff0c;计算偏移坐标 <template><div class"outbox"><label>角度: <input v-model.number"rotate" type"number" /></label><br><div c…

Docker容器安装软件(完整版)

文章目录 一、安装Docker1.1 docker 相关的命令1.2 配置镜像加速 二. 安装es2.1 创建网络2.2 拉取镜像2.3 创建挂载点目录2.4 部署单点es&#xff0c;创建es容器2.5 编写elasticsearch.yml2.6 重启es容器2.7 测试Elasticsearch是否安装成功 三. 基于Docker安装Kibana3.1 拉取镜…