【问题标题】:Splitting file lines and save them in a file拆分文件行并将它们保存在文件中
【发布时间】:2018-04-01 16:50:02
【问题描述】:

我在文本文件中有 1000 个 SQL 选择查询。例如下面的查询:

select first_name, title, salary
from employees, salaries
where
    employees.emp_no = salaries.emp_no
    and first_name = 'attila'
    and last_name = '1UB4pqakE3'

我想以这种形式将它保存在另一个文件中:

(first_name,title,salary,employees.emp_no,salary.emp_no,last_name)

我的意思是我想处理原始文件的每一行以仅保留属性。我想知道如何在 Python 中做到这一点?

【问题讨论】:

  • 欢迎来到 SO。您应该编写一个 MCVE 并展示一些努力。可以编辑您的帖子以生成文件的精简样本。

标签: python sql


【解决方案1】:

这里使用正则表达式和集合/列表理解来解决您的问题。

首先将文件加载到变量中:

with open('some_query.sql') as file:
    txt = file.read()

然后标记内容,删除文本值(以'开头)和SQL关键字:

import re

# Tokenize words
regex = re.compile("([\w._']+)")
tokens = regex.findall(txt)

# Set Comprehension removing text fields:
tokens = { token for token in tokens if not(token.startswith("'")) }

# SQL Keywords:
keywords = {'select', 'from', 'where', 'limit', 'and', 'or', 'not'}

# Identifiers:
identifiers = tokens - keywords

对于您的试用样本,它会返回:

{'employees',
 'employees.emp_no',
 'first_name',
 'last_name',
 'salaries',
 'salaries.emp_no',
 'salary',
 'title'}

这是没有重复的列标识符的排序列表。

如果出现的顺序真的很重要并且允许重复(如您的输出所示),那么只需将上面的代码更改为效率较低的代码:

# Set Comprehension removing text fields:
tokens = [ token for token in tokens if not(token.startswith("'")) ]

# SQL Keywords
keywords = {'select', 'from', 'where', 'limit', 'and', 'or', 'not'}

# Identifiers:
identifiers = tuple([token for token in tokens if not(token in keywords)])

这导致:

('first_name',
 'title',
 'salary',
 'employees',
 'salaries',
 'employees.emp_no',
 'salaries.emp_no',
 'first_name',
 'last_name')

最后,将set写回另一个文件:

with open('some_query.key', 'w') as file:
    file.write("\n".join(tokens))

此时只需将此代码封装在一个函数中并参数化文件名,以便将其应用于所有文件。

注意:此解决方案还捕获表标识符。

【讨论】:

  • 谢谢你亲爱的杰兰德西。对此,我真的非常感激。您能否调整代码(正则表达式部分)以跳过列表中的表名。
  • 我还有其他查询,例如 (select count(employees.emp_no) from employees,salaries where employees.emp_no=salaries.emp_no and deg='6' and title='bio' ) 和 (select count (emp_no) 来自工资,其中 title='law')。我怎样才能跳过括号,只取里面的内容。您能否更新正则表达式部分以执行此类情况。
  • @user9529190 如果您希望其他人帮助您,您必须编写一个 MCVE (stackoverflow.com/help/mcve)。
  • @user9529190 你的问题不是微不足道的,你似乎有很多用例。当您完成帖子以满足 MCVE 要求时,我可以重新考虑重构我的代码。
  • 亲爱的 Jlandercy, 这是我第二次在这里提问。我不知道你所说的 MCVE 是什么意思。我写了描述和样本。我想从 python 专业人士那里获得帮助。我没有想法,所以我问。我真的很感谢您的回复,但它并没有很好地工作或如我所愿。最好的...
猜你喜欢
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多