如何查找和选择备忘录中每个特定单词的出现?

时间:2015-05-19 11:54:16

标签: delphi text replace tmemo

我正在申请取代两种非常相似的口语的不同词语。按时间划分的单词数量可能至少达到10.000+。单词没有很大的差异,它几乎是相同的语言,但是存在差异。

所以,我设法用足够快的速度替换Memo中的单词,但我不知道如何在Memo中选择所有替换的单词,以便可以看到哪些单词被替换。这可能吗?

这就是替换单词的方式:

procedure TForm1.TranslateExecute(Sender: TObject);
var i: integer;
    S, OldPattern, NewPattern: string;
begin
  S:= Memo1.Lines.Text;

  for i := 0 to (StrListV.Count - 1) do  {StrListV is created earlier, contains words that should be replaced}
  begin        
    OldPattern:= StrListV.Strings[i];
    NewPattern:= StrListV1.Strings[i]; {StrListV1 contains new words}
    S:= FastStringReplace(S, OldPattern, NewPattern,[rfReplaceAll]);
  end;

  Memo1.BeginUpdate;
  Memo1.Clear;
  Memo1.Lines.Text:= S;
  Memo1.EndUpdate;
end;

1 个答案:

答案 0 :(得分:3)

TMemoTRichEdit都不支持多项选择,因此您无法突出显示已替换的字词。但是使用TRichEdit,您可以做的是更改您替换的单词的前景/背景颜色。

TRichEdit有一个FindText()方法(包装EM_FINDTEXT消息),返回搜索字符串的索引。在循环中调用它,或者每个找到的单词都可以选择它,设置颜色,并用新文本替换它。重复直到FindText()找不到更多匹配项。

尝试这样的事情:

uses
  RichEdit, CommDlg;

procedure TForm1.TranslateExecute(Sender: TObject);
var
  I, Pos: Integer;
  EventMask: LRESULT;
  OldPattern, NewPattern: string;
  Find: RichEdit.FINDTEXT;
  Rng: RichEdit.CHARRANGE;
  Fmt: RichEdit.CHARFORMAT2;
begin
  EventMask := SendMessage(RichEdit1.Handle, EM_SETEVENTMASK, 0, 0);
  RichEdit1.Lines.BeginUpdate;
  try
    for I := 0 to StrListV.Count - 1 do
    begin        
      OldPattern := StrListV.Strings[I];
      NewPattern := StrListV1.Strings[I];
      Pos := 0;
      repeat
        Find.chrg.cpMin := Pos;
        Find.chrg.cpMax := -1;
        Find.lpstrText := PChar(OldPattern);
        Pos := SendMessage(RichEdit1.Handle, EM_FINDTEXT, FR_DOWN or FR_WHOLEWORD, LPARAM(@Find));
        if Pos = -1 then Break;

        Rng.cpMin := Pos;
        Rng.cpMax := Pos + Length(OldPattern);

        ZeroMemory(@Fmt, SizeOf(Fmt));
        Fmt.cbSize := SizeOf(Fmt);
        Fmt.dwMask := CFM_COLOR or CFM_BACKCOLOR;
        Fmt.crTextColor := ColorToRGB(clHighlightText);
        Fmt.crBackColor := ColorToRGB(clHighlight);

        SendMessage(RichEdit1.Handle, EM_EXSETSEL, 0, LPARAM(@Rng));
        SendMessage(RichEdit1.Handle, EM_SETCHARFORMAT, SCF_SELECTION, LPARAM(@Fmt));
        SendMessage(RichEdit1.Handle, EM_REPLACESEL, 0, LPARAM(PChar(NewPattern)));

        Inc(Pos, Length(NewPattern));
      until False;
    end;
  finally
    RichEdit1.Lines.EndUpdate;
    SendMessage(RichEdit1.Handle, EM_SETEVENTMASK, 0, EventMask);
  end;
end;