我的文本文件包含例如:
1. I code
2. I eat
我想只将句子解析成一些字符串并计算字符串中的每个单词并忽略该数字。但结果我想再写一下这个数字。所以我想得到的结果是:
1. I(1) code(4)
2. I(1) eat(3)
我想。首先,我必须用'' 替换号码
function checkFirstWord2($string) {
$arr = explode(' ',trim($string));
$arrpke= str_replace($arr[0],'', $arr);
return $arrpke;
}
主程序:
$file = "C:/AppServ/www/kbbi/cobaangka.txt";
$lines = file($file);
foreach($lines as $line_num => $line) {
$first = checkFirstWord2($line);
$count = count(explode('',$first);
echo $first.'('.$count.')'; // but how to write again the number 1. and 2. ?
}
我不知道再次写下句子的数量:1.
和2.
?
请帮帮我,谢谢:)
答案 0 :(得分:1)
$file = "C:/AppServ/www/kbbi/cobaangka.txt";
$lines = file($file);
foreach($lines as $line) {
$tmp = explode('. ', $line);
$new_line = $tmp[0] . ". ";
foreach(explode(' ', $tmp[1]) as $word)
{
$new_line .= $word . "(" . strlen($word) . ") ";
}
echo $new_line;
}
测试
答案 1 :(得分:1)
你有正确的想法,但你的一些功能是错误的。
-
$file = "file.txt";
$lines = file($file);
foreach($lines as $line_num => $line) {
$line_parts = explode(' ', $line); //split the line into parts
$line_number = array_shift($line_parts);//take out the first part of the line, the number
echo $line_number . ' ';//add space so it doesn't get stcuck to other letters
//loop through each of the line parts, and count the number of letters
foreach ($line_parts as $part) {
if (empty($part)) continue; //ignore spaces if any
$part = trim($part);//some cleanup for trailing spaces
$lettercount = strlen($part);
echo "$part($lettercount) "; //print the output word by word
}
echo "<br>";
}
这将输出
1. I(1) code(4)
2. I(1) eat(3)
注意 - 如果您知道它们将始终按顺序排列,则无需单独存储行号。如果它们始终按顺序排列,则可以使用foreach循环中可用的索引。
答案 2 :(得分:0)
如果每个句子都在新的一行,那么这样的事情应该有用。
$lines = explode("\n", $string);
$der = preg_replace('/\d\. /', '', $lines);
现在print_r($der);
返回:
Array
(
[0] => I code
[1] => I eat
)
<强>解释强>
首先,我们在新行上爆炸句子:
explode("\n", $string);
这给了我们一个看起来像这样的数组:
Array
(
[0] => 1. I code
[1] => 2. I eat
)
现在你想要从句子中删除行号(我压缩它们是什么?)。为此,我们需要使用正则表达式:/\d\. /
preg_replace('/\d\. /', '', $lines);
答案 3 :(得分:0)
尝试这样的事情:
示例值:
1. I code
2. I eat
3. I sleep
4. You jump
5. They curse all
6. I saw
考虑这个例子:
$final = '';
$file = "cobaangka.txt";
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($lines as $line) {
$pieces = array_filter(explode(' ', $line)); // explode them
$line_num = array_shift($pieces); // get the line number
// each words, calculate the number of characters
$complete = array_map(function($var){
return $var.'('.strlen($var).') ';
}, $pieces);
// and finally, put them back together
$final .= $line_num .' '.implode($complete) . "\n";
}
echo '<pre>';
print_r($final);
$final
应该会产生类似的内容:
1. I(1) code(4)
2. I(1) eat(3)
3. I(1) sleep(5)
4. You(3) jump(4)
5. They(4) curse(5) all(3)
6. I(1) saw(3)