2012-06-15 62 views
1

嗨,我可以用一只手解决以下问题。我试图编写一个python脚本,从tex文件中提取数字并将它们放入另一个文件中。输入文件是这样的:从乳胶文件中提取数字

\documentclass[].... 
\begin{document} 

% More text 

\begin{figure}  
figure_info 1 
\end{figure} 

\begin{figure}  
figure_info 2 
\end{figure}  

%More text 

和输出文件应该是这样的:

\begin{figure}  
figure_info 1 
\end{figure} 

\begin{figure}  
figure_info 2 
\end{figure} 

感谢您的帮助。

回答

1

你可以用正则表达式(re模块)findall()函数来完成。需要注意的是:

  • 使用re.DOTALL标志允许“。”对那点匹配换行符,
  • “懒”运营商(在问号“ *?”),这意味着在寻找可能的最长匹配
  • 化妆的正则表达式不会贪婪地跑过去的第一\end{figure}确定你的正则表达式字符串是r'raw string',否则你必须将每个正则表达式反斜杠转义为“\\”,并将正则表达式中的文字反斜杠转义为“\\\\”。硬编码的输入字符串也是如此。

这里,我们去:

import re 

TEXT = r"""\documentclass[].... 
\begin{document} 

% More text 

\begin{figure} 
figure_info 1 
\end{figure} 

\begin{figure} 
figure_info 2 
\end{figure} 

%More text 
""" 

RE = r'(\\begin\{figure\}.*?\\end\{figure\})' 

m = re.findall(RE, TEXT, re.DOTALL) 

if m: 
    for match in m: 
     print match 
     print '' #blank line 
0
import re 

# re.M means match across line boundaries 
# re.DOTALL means the . wildcard matches \n newlines as well 
pattern = re.compile('\\\\begin\{figure\}.*?\\\\end\{figure\}', re.M|re.DOTALL) 

# 'with' is the preferred way of opening files; it 
# ensures they are always properly closed 
with open("file1.tex") as inf, open("fileout.tex","w") as outf: 
    for match in pattern.findall(inf.read()): 
     outf.write(match) 
     outf.write("\n\n") 

编辑:发现问题 - 不是在正则表达式,但在测试文本,我匹配对(我忘了躲避\ B的在里面)。

+0

感谢您的回复和编辑! – copiancestral

0

我可能会采取简单的方法,并将整个文件读入字符串变量。对于我终于做到了这样的答案

your_script.py > output_file.tex 
2

多谢:此

import string 

f = open('/tmp/workfile', 'r') 
f = f.read() 

text = string.split(f,"\begin{figure} ") 

text.pop(0) 

for a in text: 
    a = string.split(a,"\end{figure}") 
    print "\begin{figure}\n" 
    print a[0] 
    print "\end{figure}" 

你可以从这样的命令行执行此操作。它可能不是最佳的方式,但它的工作原理。我尝试了几种建议的解决方案,但他们需要一些调整才能让它们工作。

infile = open('data.tex', 'r') 
outfile = open('result.tex', 'w') 
extract_block = False 
for line in infile: 
    if 'begin{figure}' in line: 
     extract_block = True 
    if extract_block: 
     outfile.write(line) 
    if 'end{figure}' in line: 
     extract_block = False 
     outfile.write("------------------------------------------\n\n") 

infile.close() 
outfile.close() 
+0

+1也适用:) – gauden