php - 如何将此文本转换为所需的数组格式并以 csv 格式导出?
问题描述
我使用pdftotext
工具从 pdf 中提取了这段文本
请在下面找到文本结构
stage title1 title2 title3 title4
I value1 value2 value3
II value5 value6
stage Other1 Other2 Other3 Other4
I otherval1 otherval2 otherval3 otherval4
现在我想以这种方式使用适当的列和标题以 CSV 格式导出此文本,或者以这种方式构建一个数组
[
"category" => "title1",
"score" => "value1",
],
[
"category" => "title2",
"score" => "value2",
],
[
"category" => "title3",
"score" => "value3"
],
// unable to to do this
[
"category" => "title3",
"score" => "value5"
],
[
"category" => "title4",
"score" => "value6",
],
.
.
// so on
现在的问题是
- I 阶段和 II 阶段中的列值是可选的,但任何一行中的每一列都将包含至少一个值
- 第二阶段排是可选的,可能存在或不存在
- 如果阶段 II 行存在,则该行中至少存在一个列值
我面临的问题是如何映射
- value5 到 title3
- value6 到 title4
这是我的解析器代码(PHP)
$rows = explode("\n", $pdfExtractedText);
$rows = array_values(array_filter($rows));
$categories = array_values(array_filter(explode(" ", $rows[7])));
$stage1Scores = array_values(array_filter(explode(" ", $rows[8])));
$stage2Scores = array_values(array_filter(explode(" ", $rows[9])));
var_dump($categories);
var_dump($stage1Scores);
var_dump($stage2Scores);
输出:
// categories
array:13 [
0 => "stage"
1 => "title1"
2 => "title2"
3 => "title3"
4 => "title4"
]
//values - Index preserved so that I can map with categories
array:14 [
0 => "I"
1 => "value1"
2 => "value2"
3 => "value3"
4 => "value4"
]
// index not preserved :(
array:2 [
0 => "II"
1 => "value5",
2 => "value6"
]
解决方案
那就试试这个
$csv = "";
$csv .= implode("," , $categories) . PHP_EOL;
$csv .= implode("," , $stage1scores) . PHP_EOL;
$csv .= implode("," , $stage2scores) . PHP_EOL;
然后将其写入文件。
推荐阅读
- c++ - C++ 从不引用静态类的静态成员。它会被确定初始化还是可以从二进制文件中省略?
- reactjs - 如何使用 react 和 firebase 更新 CountJS 的值
- javafx - 用于按字符操作长字符串的最佳 JavaFx 容器
- sql-server - SSRS 2016 报告服务器错误:对象引用未设置为对象的实例
- bash - `docker build`结果->“无法读取CA证书:权限被拒绝”通过shell脚本,但可以在终端
- arrays - 将元素附加到bash中的数组
- typescript - 如果字符串与数组中的字符串相同,如何在 Typescript 中设置过滤器以过滤掉字符串?
- reactjs - 异步调用后状态变为未定义
- django - django booleanfield 是 None 而不是 False
- reactjs - 如何修复'找不到模块'babel-types'