对于如何从查询中对元组进行排序,我找不到明确的示例。这是我的全部代码:
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
),并在列中显示相应的值。)
['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
其中tore
为there
,ngaming
为all
,sittam
为we
,如您所见,第3行不按顺序排列为['we', 'all', 'there']
。我的意思是,从查询中,如何根据第一行['we', 'all', 'there']
的列表顺序对输出进行排序?我还想消除输出的最后一行中的符号[('',),]
。这个程序倾向于将输入的句子翻译成另一种语言,如菲律宾的母语Ybanag
。
发布于 2015-02-09 06:30:00
您还需要在SQL中选择英文单词,以便您的第3行是(英语,ybanag)元组的列表。通过这种方式,您可以将其转换为字典,并对输入列表中的每个单词进行迭代,按顺序检索Ybanag等价物:
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])
这并不能解决数据库中找不到的单词的问题,如果您试图转换一个包含多个单词的长句,它也不能很好地扩展。
https://stackoverflow.com/questions/28403607
复制相似问题