这里使用正则表达式和集合/列表理解来解决您的问题。
首先将文件加载到变量中:
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))
此时只需将此代码封装在一个函数中并参数化文件名,以便将其应用于所有文件。
注意:此解决方案还捕获表标识符。