在Textctrl中输入带有换行的文本,通过自定义的搜索函数,会出现索引错误的问题,以下是我的原来的代码
def search_text(self, event):
print('搜索文本!')
keyword = event.GetString()
if keyword == self.pre_keyword:
if self.pre_search_selection == len(self.search_result)-1:
self.pre_search_selection = 0
else:
self.pre_search_selection += 1
else:
self.pre_keyword = keyword
text = self.text.GetValue()
self.search_result = [i.span() for i in re.finditer(keyword, text)]
self.pre_search_selection = 0
if self.search_result:
info_text = '{0}/{1}个匹配项'.format(str(self.pre_search_selection+1), str(len(self.search_result)))
self.search_info.SetLabelMarkup("<span color='GREY'>"+info_text+"</span>")
self.text.SetSelection(*self.search_result[self.pre_search_selection])
else:
info_text = '0个匹配项'
self.search_info.SetLabelMarkup("<span color='GREY'>" + info_text + "</span>")
self.text.SetSelection(0,0)
主要用到的是self.text.GetValue()来获取输入框中的文本,然后用SetSelection来选择re.finditer找到的索引位置。可是实际索引却会把\n识别为两个字符
这是因为windows系统下和Unix系统下换行符的不一致,windows是\r\n
而Unix则是\n
这个问题在Wxpython的官方文档中也有提到
因此我们把文本内容中的换行符全部替换为\r\n
即可
text = self.text.GetValue()
text = text.replace('\r\n','\n') #为了防止反复被替换,先统一
text = text.replace('\n','\r\n')