正如 ceejayoz 已经指出的那样,这不适合单个函数。您在问题中所描述的内容(检测句子中引号转义部分的语法功能 - 即“我认为情况很严重并且正在恶化”与“国情咨文”)最好通过图书馆来解决可以将自然语言分解为标记。我不知道 PHP 中有任何这样的库,但你可以看看你将在 python 中使用的项目的大小:http://www.nltk.org/ 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) ""
}
}