2017-04-03 91 views
1

我想用Python從temp.txt文件中提取頭文件定義的文本塊。如何使用Python提取兩個字符串之間的文本?

TEMP.TXT是如下,其中頭1(年)和標題2(月)被分隔符分隔「標籤=/T」:

header1="2016"/theader2="Jan" 
Lion Animal 
Apple Food 
.end 

header1="2016"/theader2="Feb" 
Tiger Animal 
Orange Food 
.end 

我寫了一個腳本如下效果很好(CMD :python script.py [year] with argvs),但是這允許我僅提取指定的(月份,年份)數據,並且限制通配符月份(或年份)來提取所有文本。 (例如,如果我嘗試使用python script.py [year] *通配符月份,它將不起作用。)有更好的方法嗎?

import pandas as pd 
import re 
import sys 

year = sys.argv[1] 
month =sys.argv[2] 

with open('./temp.txt') as infile, open('./output', 'w') as outfile: 
    copy = False 
    for line in infile: 
     if line.strip() == 'header1="%s"\theader2="%s"' % (year,month): 
      copy = True 
     elif line.strip() == '.end': 
      copy = False 
     elif copy: 
      outfile.write(line) 

pd.read_csv('./output', encoding='utf8', sep='\;', dtype='unicode').to_excel('./output.xlsx', sheet_name='sheet2', index=False) 

回答

0

你可以添加通配符腳本:

if ((year == '*' or ('header1="%s"' % year) in line.strip()) and 
    (month == '*' or ('header2="%s"' % month) in line.strip()) 
    ): 
    copy = True 

你需要逃跑或引用慶典時調用,這樣它不會擴展到文件列表,爲星號例如:

python script.py [year] \* 
python script.py [year] '*' 

程序的總體形狀是正確的,雖然在最低限度,你需要:

  • 迭代通過行無論你在一個匹配塊
  • 跟蹤或在需要時不
  • 寫入outfile中

你的腳本幾乎做到了這一點,所以我不會」不用太擔心優化它。

+0

謝謝,這真的有助於解決問題! – cinemania

相關問題