鍍金池/ 問答/Python  C++/ Python 從多行中提取特定字符串

Python 從多行中提取特定字符串

我有一個 sql 文本,我想把其中的 sql 逐個提取出來

文本例如:

select xxxx from aaaa where bbb=123;
select yyy from
aaaa where
 bbb=123;
…
…

每一個 sql 都是以 select 開始,; 分號結(jié)束。一個 SQL 可以是一行,也可以是多行。
請教各位專家,這個在 Python3 中如何高效的實現(xiàn)?

回答
編輯回答
夏木

re.compile(r"select.*?from.*?where.*?;", re.S|re.M)?

2017年2月2日 03:34
編輯回答
我甘愿
def get_txt_sql(file_path):
    with open(file_path) as f:
        data = f.read()
        return data.split(';')
2018年5月29日 21:01
編輯回答
痞性
# -*- coding:utf-8 -*-

sqls = []

def get_txt_sql(file_path):
    with open(file_path) as f:
        with_aline = ""
        for line in f:
            with_aline += " " + line.rstrip("\n")
            if with_aline.endswith(";\n") or with_aline.endswith(";"):
                sqls.append(with_aline.strip("\n").strip())
                with_aline = ""


if __name__ == "__main__":
    get_txt_sql("./sql.txt")
    print(sqls)
2018年5月5日 09:35