Python Forum
Split the list and obtain a single value - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Split the list and obtain a single value (/thread-19727.html)



Split the list and obtain a single value - Gururaj - Jul-11-2019

Hi everyone,

I am gururaj deshpande (new user), i started using python recently for my college project purpose. My query is regarding SQL query parsing, i am using the open source API sqlparse to parse the given SQL query. The output I am getting is in the form of a tokenlist which looks somewhat like this
[<DML 'select' at 0x7FF7F1114E88>, <Whitespace ' ' at 0x7FF7F1114EF0>, <IdentifierList 'name,p...' at 0x7FF7F0D8A5D0>, <Whitespace ' ' at 0x7FF7F0D8D1F0>, <Keyword 'from' at 0x7FF7F1114E20>, <Whitespace ' ' at 0x7FF7F0D8D2C0>, <Identifier 'employ...' at 0x7FF7F0D8A4D0>, <Whitespace ' ' at 0x7FF7F0D8D390>, <Where 'where ...' at 0x7FF7F10CDED0>]
I want to extract only the single values from the obtained list for ex,only "select", "from" etc in the above given case.
Can anyone please help me with this issue? any suggestions are appreciated.

Thank you,
Guru


RE: Split the list and obtain a single value - scidam - Jul-12-2019

I've never used sqlparse before. Nevertheless, exploring its source code might lead to the following solution, e.g.
import sqlparse
from sqlparse.tokens import Token  # look at source of tokens.py
raw = 'select * from foo; select * from bar;'
parsed = sqlparse.parse(raw)
list(filter(lambda x: x.ttype in [Token.Keyword, Token.Keyword.DML], parsed[0].tokens))
Output:
[<DML 'select' at 0x7F732037EEE8>, <Keyword 'from' at 0x7F732039F0A8>]