首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何根据列表值从查询中对元组列表进行排序?

如何根据列表值从查询中对元组列表进行排序?
EN

Stack Overflow用户
提问于 2015-02-09 05:55:08
回答 1查看 96关注 0票数 1

对于如何从查询中对元组进行排序,我找不到明确的示例。这是我的全部代码:

代码语言:javascript
运行
复制
import nltk //http://www.nltk.org/
import pypyodbc

text = raw_input()
token = nltk.word_tokenize(text)
print(token)
tagged = nltk.pos_tag(token)
print(tagged)


class Database(object):
    def __init__(self):
        self.connected = False
        self.conn = None
        self.cur = None

    def connect(self):
        if not self.connected:
            self.conn = pypyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=Dictionary')
            self.connected = True
            self.cur = self.conn.cursor()

    def search(self, lists):
        if not self.connected:
            self.connect()
        for word in lists:
            self.cur.execute('SELECT Ybanag FROM Words WHERE English IN (%s)' % (",".join('?'*len(lists))), lists)
            result = self.cur.fetchall()
            return result

get = Database()
this = get.search(token)
print(this)

这段代码的输出是:(例如,我输入了这个句子:we all there)(我使用Server创建了数据库。表名:Words,列:English, Ybanag, POST),并在列中显示相应的值。)

代码语言:javascript
运行
复制
['we', 'all', 'there'] //tokenize sentence
[('we', 'PRP'), ('all', 'DT'), ('there', 'RB')] //tokens and their POST(Part-Of-Speech Tag)
[('tore',), ('ngaming',), ('sittam',)] //their corresponding value in Ybanag from the dictionary 

其中toretherengamingallsittamwe,如您所见,第3行不按顺序排列为['we', 'all', 'there']。我的意思是,从查询中,如何根据第一行['we', 'all', 'there']的列表顺序对输出进行排序?我还想消除输出的最后一行中的符号[('',),]。这个程序倾向于将输入的句子翻译成另一种语言,如菲律宾的母语Ybanag

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-09 06:30:00

您还需要在SQL中选择英文单词,以便您的第3行是(英语,ybanag)元组的列表。通过这种方式,您可以将其转换为字典,并对输入列表中的每个单词进行迭代,按顺序检索Ybanag等价物:

代码语言:javascript
运行
复制
self.cur.execute('SELECT English,Ybanag FROM Words WHERE English IN (%s)' % (",".join('?'*len(lists))), lists)
resultDict=dict(self.cur.fetchall())
outList=[]
for word in lists:
    outList.append(resultDict[word])

这并不能解决数据库中找不到的单词的问题,如果您试图转换一个包含多个单词的长句,它也不能很好地扩展。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28403607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档