php:根据字符串中字符的位置获取单词坐标(句子编号,单词编号)


php: get the word coordinates (sentence num, word num) by position of character in the string

我很好奇关于性能的问题。

有一个php字符串$text,它包含几个句子的英文文本。为了简化这个问题,让我们猜每个句子总是以"."结尾,并且没有其他符号像!等等。

$sentences = array();
$sentences = explode(". ",  $text);//we split the text into array of sentences
$words = array();
for ($i=0; $i<count($sentences); $i++){
   $words[$i] = explode(" ",  $sentences[$i]);//split each sentence into words
}

因此,$words是一个二维阵列。

$words[$i][$j]是句子#i中的单词#j。正确的

问题是:

通过字符串中字母的位置来查找单词坐标的最快方法是什么?

所以,如果我们有文本:

I go to school. And you.

$word = positionFinder(0);//I  $word == array(0,0)  - the zero word in the zero sentence
$word = positionFinder(1);//' ' $word == array(-1," ")  or something like that
$word = positionFinder(6);//to $word == array(0,2)
$word = positionFinder(9);//school $word == array(0,3)
$word = positionFinder(10);//school $word == array(0,3)
$word = positionFinder(14);//. $word == array (-1,".") or something like that
$word = positionFinder(17);//And $word == array(1,0) - the zero word in the first sentence

我相信为了获得更好的性能,可以使用附加阵列中的一些数据。positionFinder函数的使用次数将超过文本中的字数。因此positionFinder应该尽可能快地工作。

所以它是通过字母来找到单词的坐标。有什么想法吗?

谢谢。

您可以执行以下操作:

function positionFinder($text, $n) {
    $s=$text[$n];
    $i=0;
    $sep = array(" ", ".")
    while (!in_array($text[$n-$i],$sep)) {
        $s = $text[$n+$i].$s;
        $i++;
    }
    $i=1
    while (!in_array($text[$n+$i],$sep)) {
        $s .= $text[$n+$i];
        $i++;
    }
    return s;
}

但是如果你创建一个类似的"positionFinder"数组会更快

function makearray($text) {
    $sentences = explode(". ",  $text);
    $positionFinder = array();
    $slen = 0;
    for ($i=0; $i<count($sentences); $i++) {
       $words[$i] = explode(" ",  $sentences[$i]);
       for ($ii=0; $ii<count($words[$i]); $ii++) {
           $positionFinder[$slen] = $words[$i][$ii];
           $slen += strlen($words[$i])+1; //+1 because of " "
       }
       $slen+=strlen($sentences[$i])+2; //+2 because of ". "
    }
    return $positionFinder;
}

我需要一段时间来制作阵列,但检查它会很快:

$text="I go to school. And you. ";
$positionFinder = makearray($text);
echo $positionFinder[0];
>>  I
echo $positionFinder[2];
>>  go
...