簡體   English   中英

如何使用Python在兩個字符串之間提取文本?

[英]How do you extract texts between two strings using Python?

我想使用Python從temp.txt文件中提取由頭文件定義的文本塊。

temp.txt如下所示,其中header1(year)和header2(month)由分隔符'tab = / t'分隔:

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

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

我編寫了一個腳本,如下所示(cmd:python script.py [year] [month] 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)

您可以在腳本中添加通配符:

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

從bash調用時,您需要轉義或引用星號,以便它不會擴展到文件列表,例如:

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

你的程序的一般形狀是正確的,但至少你需要:

  • 迭代線
  • 跟蹤你是否在匹配區塊
  • 必要時寫入outfile

你的腳本幾乎就是這樣,所以我不會太擔心優化它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM