本文将使用 php 和 linux sort 命令两种方法,分别实现文件内容去重及排序,并提供完成演示代码。
1.创建测试文件
写入1000000个数字,每行一个数字
<?php$file = 'user_id.txt';$num = 1000000;$tmp = '';for($i=0; $i<$num; $i++){ $tmp .= mt_rand(0,999999).PHP_EOL; if($i>0 && $i%1000==0 || $i==$num-1){ file_put_contents($file, $tmp, FILE_APPEND); $tmp = ''; }}?>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
查看文件行数
wc -l user_id.txt 1000000 user_id.txt
- 1
- 2
2.php实现去重及排序
因要处理1000000行数据,因此将php可使用的内存设置为256m,防止执行过程中内存不足。
<?php/** * 文件内容去重及排序 * @param String $source 源文件 * @param String $dest 目标文件 * @param String $order 排序顺序 * @param Int $sort_flag 排序类型 */function fileUniSort($source, $dest, $order='asc', $sort_flag=SORT_NUMERIC){ // 读取文件内容 $file_data = file_get_contents($source); // 文件内容按行分割为数组 $file_data_arr = explode(PHP_EOL, $file_data); // 去除空行数据 $file_data_arr = array_filter($file_data_arr, 'filter'); // 去重 $file_data_arr = array_flip($file_data_arr); $file_data_arr = array_flip($file_data_arr); // 排序 if($order=='asc'){ sort($file_data_arr, $sort_flag); }else{ rsort($file_data_arr, $sort_flag); } // 数组合拼为文件内容 $file_data = implode(PHP_EOL, $file_data_arr).PHP_EOL; // 写入文件 file_put_contents($dest, $file_data, true);}// 过滤空行function filter($data){ if(!$data && $data!=='0'){ return false; } return true;}// 设置可使用内存为256mini_set('memory_limit', '256m');$source = 'user_id.txt';$dest = 'php_sort_user_id.txt';fileUniSort($source, $dest);?>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
查看去重及排序后的文件
wc -l php_sort_user_id.txt 632042 php_sort_user_id.txthead php_sort_user_id.txt 012357891112...
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
3.linux sort命令实现去重及排序
linux sort命令用于文本文件按行排序
格式:
sort [OPTION]... [FILE]...
- 1
参数说明:
-u 去重
-n 数字排序类型
-r 降序
-o 输出文件的路径
使用sort执行去重及排序
sort -uno linux_sort_user_id.txt user_id.txt
- 1
查看去重及排序后的文件
wc -l linux_sort_user_id.txt 632042 linux_sort_user_id.txthead linux_sort_user_id.txt 012357891112...
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
总结:使用php或linux sort命令都可以实现文件去重及排序,执行时间上相差不大,但建议对于文件类的操作,直接使用系统命令实现更为简单。
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow