首页 > 解决方案 > 从没有空格的字符串中提取有效单词

问题描述

我有一个包含有效单词的字符串(由 确认pspell_check),但它们中没有空格。

这是结果pspell_check

regProfileAddProRec -> false (upper case added for semantics. actual word is mixed case)
reg -> true
profile -> true
add -> true
pro -> true
rec -> true
regprofile` -> true (with pspell_config_runtogether)
regprofileadd -> false

因此,正如您所见,每个单词本身都是正确的。如果我们只用pspell_config_runtogether它检查两个词是true

所以我尝试使用以下内容从字符串中提取单词:


$wordArr = [];
$word = '';
foreach (str_split($string) as $char) {
    $word .= $char;
    if(strlen($word) == 1 ){
        ## spell_check returns true for these letters individually,
        # so I manually override this behavior
        continue;
    }
    if(pspell_check($pspell_link, $word)){
        $wordArr[] = $word;
        $word = '';
    }
}

这不起作用,因为第一个匹配是re,因此下一个单词以gas in开头,gProfileAddRec并且函数失败。

目标是 ->如果字符串中的所有单词都是有效的英文单词,则通过测试,否则失败

所以任务是检查完整的单词是否是所有有效单词的连接,并且它不包含任何无效的单词。例如。regProfileABCadd会失败,因为abc它不是一个有效的词,但regProfileAddRec会通过,因为所有的词都是有效的。

完整的代码是


$string = 'regProfileaddprorec';
$pspell_config = pspell_config_create("en");
pspell_config_runtogether($pspell_config, true);
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell_link = pspell_new_config($pspell_config);

$wordArr = [];
$word = '';
foreach (str_split($string) as $char) {
    $word .= $char;
    if(strlen($word) == 1 ){
        ## spell_check returns true for these letters individually,
        # so I manually override this behavior
        continue;
    }
    if(pspell_check($pspell_link, $word)){
        $wordArr[] = $word;
        $word = '';
    }
}

编辑(解决方案)

以防将来有人(或只是我)需要这个。

解决方案 1请查看@nice_dev 的评论。他将代码粘贴在 pastebin 上,并进行了一些明显的更改,效果很好。

解决方案 2更改aspell配置以pspell_check在这种情况下工作。pspell依赖于aspell https://www.php.net/manual/en/function.pspell-new.php

有关更多信息和示例,请查看内联手册 pspell 网站:» http://aspell.net/

所以我们可以改变 和 的run-together-limit配置ignore。这将pspell_check()只识别两个单词pspell_config_runtogether并返回true一个字母字符

run-together-limit 50 # or whatever you want (default is 2)
ignore 0 # default is 1 (did not work for me as I am still getting positives)
run-together-min 2 # default is 3
ignore-case true

可以通过aspell dump config | less
链接到aspell文档http://aspell.net/man-html/index.html检查当前配置列表

编辑 2

ignore 0未提供例外结果,单字母单词仍显示为有效。但我可以添加任意条件使其为假。

标签: phpalgorithm

解决方案


推荐阅读