正如 ceejayoz 已经指出的那样,这不适合单个函数。您在问题中描述的内容(检测句子的引号转义部分的语法功能 - 即“我认为它很严重并且它正在恶化”与“国情咨文”)最好用图书馆来解决可以将自然语言分解为标记。我不知道 PHP 中有任何此类库,但您可以查看您将在 python 中使用的项目大小:http ://www.nltk.org/
我认为您能做的最好的事情就是定义一组您手动验证的语法规则。像这样的东西怎么样:
abstract class QuotationExtractor {
protected static $instances;
public static function getAllPossibleQuotations($string) {
$possibleQuotations = array();
foreach (self::$instances as $instance) {
$possibleQuotations = array_merge(
$possibleQuotations,
$instance->extractQuotations($string)
);
}
return $possibleQuotations;
}
public function __construct() {
self::$instances[] = $this;
}
public abstract function extractQuotations($string);
}
class RegexExtractor extends QuotationExtractor {
protected $rules;
public function extractQuotations($string) {
$quotes = array();
foreach ($this->rules as $rule) {
preg_match_all($rule[0], $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$quotes[] = array(
'quote' => trim($match[$rule[1]]),
'cited' => trim($match[$rule[2]])
);
}
}
return $quotes;
}
public function addRule($regex, $quoteIndex, $authorIndex) {
$this->rules[] = array($regex, $quoteIndex, $authorIndex);
}
}
$regexExtractor = new RegexExtractor();
$regexExtractor->addRule('/"(.*?)[,.]?\h*"\h*said\h*(.*?)\./', 1, 2);
$regexExtractor->addRule('/"(.*?)\h*"(.*)said/', 1, 2);
$regexExtractor->addRule('/\.\h*(.*)(once)?\h*said[\-]*"(.*?)"/', 3, 1);
class AnotherExtractor extends Quot...
如果你有类似上面的结构,你可以通过任何/所有运行相同的文本,并列出可能的引用以选择正确的引用。我已经用这个线程运行代码作为测试的输入,结果是:
array(4) {
[0]=>
array(2) {
["quote"]=>
string(15) "Not necessarily"
["cited"]=>
string(8) "ceejayoz"
}
[1]=>
array(2) {
["quote"]=>
string(28) "They think it's `game over,'"
["cited"]=>
string(34) "one senior administration official"
}
[2]=>
array(2) {
["quote"]=>
string(46) "I think it is serious and it is deteriorating,"
["cited"]=>
string(14) "Admiral Mullen"
}
[3]=>
array(2) {
["quote"]=>
string(16) "Not necessarily,"
["cited"]=>
string(0) ""
}
}