繁体   English   中英

如何按查询的相同顺序对SQL结果进行排序(将句子分解成单词的元组)?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM