Retrieve text blocks from file

血红的双手。 提交于 2020-02-06 04:28:12

问题


In a file I've blocks of queries separated by blank lines (can be one or more blank lines). Is there a better way to get the queries into a list ?

Ex File:

select * from tbA
where colA= '2'

select * from tbB
where colB = 'c'
order by colc



select * from tbC

Code I've so far:

queries = list()
with open(sql_file_path, 'rb') as f:
    lines = f.readlines()
    i = 0
    while i < len(lines):
        query = ''
        while i < len(lines) and not lines[i].isspace():
            query += lines[i]
            i += 1
        while i < len(lines) and lines[i].isspace():
            i += 1
        queries.append(query.strip())

The result I'm looking for is a list containing the complete queries not just one line of the query.


回答1:


with open(path) as f:
    lines = [line.strip() for line in f if line]

The list comp will iterate through your file line by line and build it into the list if the line is not blank. If it is blank, it will ignore it.

As per your edited text, just split on a blank line (that is, \n\n).

with open(path) as f:
    lines = [query for query in f.read().split("\n\n") if query]

You could also do it by regex:

import re

with open(path) as f:
    queries = re.split(r"\n\n+",f.read())



回答2:


queries = [query.strip() for query in re.split(r"(\r\n)(\r\n)+", all_text, ) if query.strip()]


来源:https://stackoverflow.com/questions/21895907/retrieve-text-blocks-from-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!