闲言碎语
正则表达式是一种功能强大的字符串处理工具,几乎所有关于字符串的操作都可以用它来实现。本篇文章将展示如何使用 Python 中的正则表达式来编写 LaTeX 工具。
我们先展示效果,末尾再补充代码,将其写入 mylatex.py
即可使用本文的示例。
LaTeX 矩阵
示例
计算矩阵的 5 次幂,并导出 LaTeX 代码:
( 1 2 3 2 3 4 4 5 6 ) \begin{align*} \left(\begin{array}{ccc} 1 & 2 & 3 \\ 2 & 3 & 4 \\ 4 & 5 & 6 \end{array}\right) \end{align*} 124235346
-
输入代码如下:
from mylatex import latex_matrix mat = matrix([[1, 2, 3], [2, 3, 4], [4, 5, 6]]) # matrix 是 sagemath 自带函数 latex_matrix(list(mat^5))
-
输出的 LaTeX 代码效果:
注:本例计算使用了 sagemath,虽然 sagemath 自带的功能可以输出 LaTeX 格式,不过样式较为固定。
函数代码
def latex_matrix(mat: list, hrows=None, hcols=None, copy=True) -> str:"""生成矩阵的 LaTeX 代码Args:mat (list): 矩阵主体hrows (set, optional): 指定划线的行. 默认为 None.hcols (set, optional): 指定划线的列. 默认为 None.copy (bool, optional): 是否复制到剪贴板. 默认为 True.Returns:str: 生成的 LaTeX 代码注:hrows = {0, 1} 表示在顶行和第 1 行划线。"""# 检查输入assert len(mat), "输入为空矩阵"# 将数据转化为字符串mat = [[str(i) for i in line] for line in mat]# 行数和列数m, n = len(mat), len(mat[0])# 设置列线hcols = hcols or set()f = lambda i: '|c' if i in hcols else "c"# 设置行线hrows = hrows or set()g = lambda i: r'\\\hline' if i in hrows else r'\\'# 头部col_format = "".join(f(i) for i in range(n))if n in hcols:col_format += '|'beg = r"""\begin{align*}
\left(\begin{array}{%s}
""" % col_format# 尾部end = "\n\\end{array}\\right)\n\\end{align*}"# 内容部分content = "\\hline\n" if 0 in hrows else ""content += "\n".join(["&".join(line) + g(i) for i, line in enumerate(mat)])# 输出结果out = beg + content[:-2] + endif copy:pyperclip.copy(out)return out
Markdown 表格
Markdown 语法请参阅 一文搞懂 reST 和 Markdown 语法。下面我们讨论 Markdown 表格的生成方法,其与 LaTeX 的思路类似。
示例
-
打印表格,输入代码如下:
from mylatex import markdown_table, MDtable_to_array_table # 方法一:指定标题 content = [[1, 2, 3], [2, 3, 4]] title = ["a", "b", "c"] markdown_table(content, title=title)# 方法二:不指定标题 content = [["a", "b", "c"], [1, 2, 3], [2, 3, 4]] markdown_table(content)
-
显示效果:
a b c 1 2 3 2 3 4
注:使用
MDtable_to_array_table
可将 Markdown 格式的表格代码转换为 LaTeX 的array
形式
Python 代码
-
将列表转换为 Markdown 表格
def markdown_table(content: list, title=None, copy=True) -> str:"""将列表转化为 Markdown 表格格式Args:content (list): 表格内容title (list, optional): 表格标题,默认为 content 的第一行copy (bool, optional): 是否复制到剪贴板. 默认为 True.Returns:str: 生成的 Markdown 代码"""# 表格第二行格式(居中)align = "|".join([":-:"] * len(content[0]))# 行内元素用 | 分割content = ["|".join(str(i) for i in line) for line in content]# 设置标题if title is None: # 未定义标题,默认取第一行为标题title = content[0]content = content[1:]else:title = "|".join(str(i) for i in title)# 合并并导出文本txt = "\n".join([title, align, *content])if copy:pyperclip.copy(txt)return txt
-
将 Markdown 表格转换为 LaTeX 的
array
表格def MDtable_to_array_table(txt: str, copy=True) -> str:"""将 Markdown 格式的字符串转换为 LaTeX 数组形式Args:txt (str): Markdown 表格字符串copy (bool, optional): 是否复制到剪贴板. 默认为 True.Returns:str: 生成的 LaTeX 代码"""lines = txt.split("\n") # 按行拆分lines.pop(1) # 去掉格式行lines = [line.split("|") for line in lines]return latex_array_table(lines, copy=copy)
Dynkin 图
TODO。之前用 tikz + python 写绘图工具,做了一部分。工具完整成型再放上来。
小结
以上,我们用 Python 编写工具,以自动生成 LaTeX 和 Markdown 格式的代码。