0

下面将遍历目录中的文件,读取它们并将它们以最多 500 行的文件保存到新目录中。这对我很有用(感谢丹尼尔)但是,我需要修改。我想保存到基于 alpha num 的文件。

首先,我假设的第一步是对数组 alpha 进行数字排序(已经小写)。

获取每个 $incoming."/.txt" 中以 "a" 开头的所有行,并将它们放入 $save500."/a" 的文件夹中,但每行最多 500 行。(我想最好从排序顶部的第一个开始,所以“0”而不是“a”对吗?)

所有以数字开头的行,进入 $save500."/num"。

除了 a-z0-9 之外,所有行都不会以其他任何内容开头。

这将允许我使用这种平面文件方法更有效地搜索我的文件以查找匹配项。将其缩小到一个文件夹。

$nextfile=0;
    if (glob("" . $incoming . "/*.txt") != false){
     $nextfile = count(glob("" . $save500 . "/*.txt"));
     $nextfile++;
    }
    else{$nextfile = 1;}
    /**/
     $files = glob($incoming."/*.txt");
     $lines = array();
     foreach($files as $file){
     $lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
    }
     $lines = array_unique($lines);
    /*this would put them all in one file*/
    /*file_put_contents($dirname."/done/allofthem.txt", implode("\n", $lines));*/
    /*this breaks them into files of 500*/
     foreach (array_chunk($lines, 500) as $chunk){
     file_put_contents($save500 . "/" . $nextfile . ".txt", implode("\n", $chunk));
     $nextfile++;
    }

每个仍然需要最多 500 行。

我稍后将毕业到mysql。现在才这样做几个月。

好像这还不够。我什至想把前两个字符去掉。使用 subs a/0 到 z/z 制作目录!

由于没有回应,可能是上面的错误方法。

但我想将 aardvark 之类的单词保存到 1.txt 的 a/a 文件夹(附加)。除非 1.txt 有 500 行,否则将其保存到 a/a 2.txt。

因此,除非有 500 行,否则 xenia 将被附加到 x/e 文件夹 1.txt 文件中,因此创建 2.txt 并将其保存在那里。

然后,我将能够更有效地搜索这些单词,而无需将大量内容加载到内存中或循环遍历不包含匹配项的文件/行。

感谢大家!

4

1 回答 1

1

我在这里写了一些代码,应该可以满足您的需求,它不是性能美,但应该可以完成工作。在安全的环境中尝试,不保证任何数据丢失;)

如果有任何错误,请发表评论,这里已经很晚了;)我要睡觉了;)

注意:这个只有在每行至少有 2 个字符时才有效!;)

$nextfile=0;

if (glob("" . $incoming . "/*.txt") != false){
  $nextfile = count(glob("" . $save500 . "/*.txt"));
  $nextfile++;
}
else
{
  $nextfile = 1;
}



$files = glob($incoming."/*.txt");
$lines = array();
foreach($files as $file){
  $lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
}


$lines = array_unique($lines);


/*this would put them all in one file*/
/*file_put_contents($dirname."/done/allofthem.txt", implode("\n", $lines));*/
/*this breaks them into files of 500*/

// sort array
sort($lines);

// outer grouping
$groups     = groupArray($lines, 0);
$group_keys = array_keys($groups);

foreach($group_keys as $cKey) {
  // inner grouping
  $groups[$cKey] = groupArray($groups[$cKey], 1);

  foreach($groups[$cKey] as $innerKey => $innerArray) {
    $nextfile = 1;
    foreach(array_chunk($innerArray, 500) as $chunk) {
      file_put_contents($save500 . "/" . $cKey . "/" . $innerKey . "/" . $nextfile . ".txt", implode("\n", $chunk));    
      $nextfile++;
    }
  }

}


function groupArray($data, $offset) {

  $grouped = array();

  foreach($data as $cLine) {
    $key = substr($cLine, $offset, 1);
    if(!isset($grouped[$key])) {
      $grouped[$key] = array($cLine);
    } 
    else
    {
      $grouped[$key][] = $cLine;
    }
  }

  return $grouped;
}
于 2010-09-13T23:38:45.697 回答