微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Delphi的拼写检查组件

我们为社区开发的Twitter客户端的一个要求是拼写检查组件.您在应用程序中使用了哪些拼写检查组件/系统以及使用它的经验是什么?

解决方法

Windows附带拼写检查API(Windows 8).
twindow8SpellChecker = class(TCustomSpellChecker)
private
    FSpellChecker: ISpellChecker;
public
    constructor Create(LanguageTag: UnicodeString='en-US');

    procedure Check(const text: UnicodeString; const Errors: TList); override; //gives a list of TSpellingError objects
    function Suggest(const word: UnicodeString; const Suggestions: TStrings): Boolean; override;
end;

实施:

constructor twindow8SpellChecker.Create(LanguageTag: UnicodeString='en-US');
var
    factory: ISpellCheckerFactory;
begin
    inherited Create;

    factory := CoSpellCheckerFactory.Create;
    OleCheck(factory.CreateSpellChecker(LanguageTag,{out}FSpellChecker));
end;

procedure twindow8SpellChecker.Check(const text: UnicodeString; const Errors: TList);
var
    enumErrors: IEnumSpellingError;
    error: ISpellingError;
    spellingError: TSpellingError;
begin
    if text = '' then
        Exit;

    OleCheck(FSpellChecker.Check(text,{out}enumErrors));

    while (enumErrors.Next({out}error) = S_OK) do
    begin
        spellingError := TSpellingError.Create(
                error.StartIndex,error.Length,error.CorrectiveAction,error.Replacement);
        Errors.Add(spellingError);
    end;
end;

function twindow8SpellChecker.Suggest(const word: UnicodeString; const Suggestions: TStrings): Boolean;
var
    hr: HRESULT;
    enumSuggestions: IEnumString;
    ws: PWideChar;
    fetched: LongInt;
begin
    if (word = '') then
    begin
        Result := False;
        Exit;
    end;

    hr := FSpellChecker.Suggest(word,{out}enumSuggestions);
    OleCheck(hr);

    Result := (hr = S_OK); //returns S_FALSE if the word is spelled correctly

    ws := '';
    while enumSuggestions.Next(1,{out}ws,{out}@fetched) = S_OK do
    begin
        if fetched < 1 then
            Continue;

        Suggestions.Add(ws);

        CoTaskMemFree(ws);
    end;
end;

TSpellingError对象是一个围绕四个值的简单包装:

TSpellingError = class(TObject)
protected
    FStartIndex: ULONG;
    FLength: ULONG;
    FCorrectiveAction: CORRECTIVE_ACTION;
    FReplacement: UnicodeString;
public
    constructor Create(StartIndex,Length: ULONG; CorrectiveAction: CORRECTIVE_ACTION; Replacement: UnicodeString);
    property StartIndex: ULONG read FStartIndex;
    property Length: ULONG read FLength;
    property CorrectiveAction: CORRECTIVE_ACTION read FCorrectiveAction;
    property Replacement: UnicodeString read FReplacement;
end;

原文地址:https://www.jb51.cc/delphi/102054.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐