gpt4 book ai didi

php - 我们如何从文件中获取文本(逐字)到 PHP 中的二维数组中?

转载 作者:行者123 更新时间:2023-12-03 23:01:26 25 4
gpt4 key购买 nike

我有一个文本文件,其中包含一些我想放入二维数组中的内容。该文本文件由等长的句子组成。如何将每个单词放入数组?

文本文件的例子是-

This is stackoverflow

I am user

这个文件每行包含3个词

This - at [0][0] position
is - at [0][1] position
stackoverflow - at [0][2] position

I - at [1][0] position
am - at [1][1] position
user - at [1][2] position

我做了类似的东西,但似乎没有成功。

$word_count = $word_length = 0;

if ($fh = fopen('array.txt','r')) {
while (! feof($fh)) {
if ($s = fgets($fh,1048576)) {
$words = preg_split('/\s+/',$s,-1,PREG_SPLIT_NO_EMPTY);
foreach ($words as $word) {
$word_count++;
$word_length += strlen($word);

$array = array();
for($i=$a;$i<($word_count/4);$i++)
{
for($j=$b;$j<4;$j++)
{
$array[$i][$j]=$words[$j];
}
}
}
}
}
}

如有任何帮助,我们将不胜感激。谢谢

最佳答案

这应该适合你:

只需使用 file()explode() 将您的文件读入一个数组,每行使用 array_map() 一个空格。

$lines = array_map(function($v){
return explode(" ", $v);
}, file("yourTextFile.txt", FILE_IGNORE_NEW_LINES |FILE_SKIP_EMPTY_LINES));

关于php - 我们如何从文件中获取文本(逐字)到 PHP 中的二维数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30874901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com