4八/101
矩阵、表格转换成latex表格通用版Python程序
上周写了通过Python轻松把矩阵转换成latex代码,其中的Python程序,特殊性很强,不够通用,原因在于“for i in [3,2]”和“content=content[3:-3]”这两句。
经过修改,得到了一个比较通用的Python程序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import re f=open('matrix.txt','r') content=f.readlines() n=len(content) f.close() fraction_re=re.compile(r"(?P<numerator>\d+)/(?P<denominator>\d+)") space_re=re.compile(r"\s+") for i in range(0,n): content[i]=content[i].lstrip() content[i]=content[i].rstrip() content[i]=fraction_re.sub(r"\\frac{\g<numerator>}{\g<denominator>}",content[i]) content[i]=space_re.sub('&',content[i]) content[i]=content[i]+"\\\\\n" content[n-1]=content[n-1].replace("\n",'') f=open('mresult.txt','w') f.writelines(content) f.close() |
解释如下:
- f=open('matrix.txt','r') 这里使用的是相对路径。.txt文件和.py路径在同一目录下,即可使用。上篇程序里使用的是绝对路径。另外注意,在Windows复制的路径是使用“\”,而Python程序中使用的是“/”。
- content=f.readlines() 这里content是一个list,每一项是“.txt"的一行。上篇程序里使用的是content=f.read(),content就是一个字符串。
- fraction_re=re.compile(r"(?P<numerator>\d+)/(?P<denominator>\d+)") 括号中便是大名鼎鼎的正则表达式。其实,在Word查找中也有简易的正则表达式,但是没有 ?P<name>。这一句是为找到的内容命名,便于以后调用。
- content[i]=content[i].lstrip() 这一句的功能是去掉字符串开始的空格。.rstrip()是去掉末尾的空格。
下面是表格变latex代码的程序,和矩阵变latex代码差不多,就是行末多了"\hline"而已。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import re f=open('table.txt','r') content=f.readlines() n=len(content) f.close() fraction_re=re.compile(r"(?P<numerator>\d+)/(?P<denominator>\d+)") space_re=re.compile(r"\s+") for i in range(0,n): content[i]=content[i].lstrip() content[i]=content[i].rstrip() content[i]=fraction_re.sub(r"\\frac{\g<numerator>}{\g<denominator>}",content[i]) content[i]=space_re.sub('&',content[i]) content[i]=content[i]+"\\\\\\hline\n" content[n-1]=content[n-1].replace("\n",'') content[0]="\hline\n"+content[0] f=open('tresult.txt','w') f.writelines(content) f.close() |
原创文章,转载请注明: 转载自ELLY66
本文链接地址: 矩阵、表格转换成latex表格通用版Python程序
文章的脚注信息由WordPress的wp-posturl插件自动生成
Evernote lets you save all the interesting things you see online into a single place. Access all those saved pages from your computer, phone or the web. Sign up now or learn more. It's free!
2010年08月22日 08:16
I’ve recently started a blog, the information you provide on this site has helped me tremendously. Thank you for all of your time & work.