基于百度纠错API的语段纠错系统
使用Python和Pyqt5界面实现
系统界面如下所示,可以同时揪出多个错误并同时高亮表示错误和正确的地方
百度纠错返回的对象例子如下所示:
{'vec_fragment': [{'ori_frag': '行师', 'begin_pos': 4, 'correct_frag': '行驶', 'end_pos': 8},
{'ori_frag': '行使', 'begin_pos': 20, 'correct_frag': '行驶', 'end_pos': 24},
{'ori_frag': '行施', 'begin_pos': 36, 'correct_frag': '行驶', 'end_pos': 40}], 'score': 0.760204,
'correct_query': '汽车行驶在路上,汽车行驶在路上,汽车行驶在路上'}
下边的代码,只截取了对QEdittext操作高亮标注的部分:
item即百度API返回的对象
首先在右边的edittext中显示纠错后端句子,即item['correct_query']
然后获取item中所有的出错信息
遍历每个出错的具体信息(err即错误的字符串和rig即改正后的字符串)
分别在左右连个textedit中从前往后检索出错/改正的字符串,找到即高亮标注
但因为是全文检索字符串,所以有可能会把与纠错无关的字符串找出并标注,需要改进,但还好这在一两百字的段落中不常见
主要还是记录下qt中按需查找并高亮标注多个字符串的方法,同理也可应用到qedittext的其它自定义操作中
self.textEdit_2.setPlainText(item['correct_query'])
errs=item['vec_fragment']
#左
for err in errs:
document=self.textEdit.document()
highlight_cursor=QTextCursor(document)
cursor=QTextCursor(document)
cursor.beginEditBlock()
color_format=QTextCharFormat(highlight_cursor.charFormat())
color_format.setBackground(QColor(255,211,6))
while (not highlight_cursor.isNull()) and (not highlight_cursor.atEnd()):
highlight_cursor = document.find(err['ori_frag'], highlight_cursor)
if not highlight_cursor.isNull():
highlight_cursor.mergeCharFormat(color_format)
cursor.endEditBlock()
#右
for rig in errs:
document_2 = self.textEdit_2.document()
highlight_cursor_2 = QTextCursor(document_2)
cursor_2 = QTextCursor(document_2)
cursor_2.beginEditBlock()
color_format = QTextCharFormat(highlight_cursor_2.charFormat())
color_format.setBackground(QColor(255, 211, 6))
while (not highlight_cursor_2.isNull()) and (not highlight_cursor_2.atEnd()):
highlight_cursor_2 = document_2.find(rig['correct_frag'], highlight_cursor_2)
if not highlight_cursor_2.isNull():
highlight_cursor_2.mergeCharFormat(color_format)
cursor_2.endEditBlock()