从文件中检索文本块 [英] Retrieve text blocks from file

查看:162
本文介绍了从文件中检索文本块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个文件中,我的查询块被空行分隔(可以是一个或多个空行)。有没有更好的方式来查询到一个列表?



存档:

  SELECT * FROM TBA 
,其中可乐= '2'

SELECT * FROM TBB
,其中COLB = 'C'
以便通过COLC



select * from tbC

Code I'到目前为止已经:

 查询=列表()
相开放(sql_file_path, 'RB')为f:
lines = f.readlines()
i = 0
while i< len(行):
query =''
while I< len(lines)而不是lines [i] .isspace():
query + = lines [i]
i + = 1
while I< LEN(线)和线[I] .isspace():
I + = 1个
queries.append(query.strip())

我正在查找的结果是包含完整查询的列表,而不仅仅是查询的一行。

解决方案

 与开放(路径)作为f:
lines = [line.strip()for line in line if]

如果行不是空白的,列表组件会逐行遍历文件并将其构建到列表中。如果它是空的,它将忽略它。



根据您编辑的文本,只需在空白行(即 \\\
\ n
)。

 与开放(路径)作为f:
lines = [查询f.read()。split(\\\
\\\
)if $] b

你也可以用正则表达式来完成:

  import re 

with open(path )作为f:
queries = re.split(r\\\
\\\
+,f.read())


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.

解决方案

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())

这篇关于从文件中检索文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆