[英]How do I order my SQL results in the same order of my query (a sentence broken down into a tuple of words)?
使用Python,我希望以與查詢相同的順序從字典表中獲取結果。 我為查詢提供了一個元組,作為分解的句子(可以在數組等有序列表中執行此操作嗎?)。 我正在使用標准的MySQLdb游標(我應該嘗試其他游標嗎?),並使用它執行查詢,如下所示:
import MySQLdb
...
sent_tuple = ('The', 'opening', 'session', 'of', 'the', '5-day', 'session', 'will', 'begin', 'at', '10', 'a.m.', 'today', '.')
mysql_cursor = mysql.cursor()
query = ("SELECT DISTINCT Orthography, Transcription FROM Dictionary WHERE Orthography IN " + sent_tuple + " ORDER BY FIELD(Transcription, Orthography)")
for rows in mysql_cursor:
print rows
結果以與send_tuple中給定的順序不同的順序出現,但或多或少以字母升序出現,我猜這是SELECT語句的默認值...:
('AT', 'AE T')
('BEGIN', 'B IH G IH N')
('OF', 'AH V')
('OPENING', 'OW P AH N IH NG')
('SESSION', 'S EH SH AH N')
('THE', 'DH AH')
('TODAY', 'T AH D EY')
('WILL', 'W IH L')
('.', '.')
在字典中沒有匹配項的地方,還有一些缺失的結果。 不確定如何處理...方向???
我在StackExchange上看過一些類似的帖子,例如涉及ORDER BY,但似乎無法使它們正常工作...
我不確定是否可以在SQL中執行此操作,但是您當然可以使用原始輸入元組作為遍歷結果的索引:
from collections import OrderedDict
sent_tuple = ('The', 'opening', 'session', 'of', 'the', '5-day', 'session', 'will', 'begin', 'at', '10', 'a.m.', 'today', '.')
rows = [
('AT', 'AE T'),
('BEGIN', 'B IH G IH N'),
('OF', 'AH V'),
('OPENING', 'OW P AH N IH NG'),
('SESSION', 'S EH SH AH N'),
('THE', 'DH AH'),
('TODAY', 'T AH D EY'),
('WILL', 'W IH L'),
('.', '.'),
]
index = OrderedDict.fromkeys( i.upper() for i in sent_tuple )
rows_dict = dict(rows)
ordered_rows_gen = (
(i, rows_dict[i]) for i in index if i in rows_dict
)
for row in ordered_rows_gen:
print row
我已經使用輸入元組值作為鍵將index
創建為OrderedDict
,因為這提供了快速的有序集,並且將避免輸出中出現任何重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.