aymanrb/php-unstructured-text-parser
一个PHP库,用于从非结构化文本文档中提取文本
v2.5.0
2023-11-10 08:52 UTC
Requires (Dev)
- php-coveralls/php-coveralls: ^2.1
- phpunit/phpunit: ^8.4
This package is auto-updated.
Last update: 2024-09-10 10:47:56 UTC
README
关于非结构化文本解析器
这是一个小巧的PHP库,帮助从非结构化文档中提取文本。例如,当你想解析表单生成的邮件文本时,你可以创建一个与预期收到的邮件格式匹配的模板,指定变量文本元素,并将其余部分留给类从收到的邮件正文文本中提取预格式化的变量。
当需要从以下内容解析数据时很有用
- 从网页表单生成的电子邮件
- 具有可定义模板/表达式的文档
安装
PHP非结构化文本解析器可在Packagist上找到(使用语义版本控制),并且推荐使用Composer进行安装。将以下行添加到您的composer.json
文件中
"aymanrb/php-unstructured-text-parser": "~2.0"
或运行
composer require aymanrb/php-unstructured-text-parser
使用示例
<?php include_once __DIR__ . '/../vendor/autoload.php'; $parser = new aymanrb\UnstructuredTextParser\TextParser('/path/to/templatesDirectory'); $textToParse = 'Text to be parsed fetched from a file, mail, web service, or even added directly to the a string variable like this'; //performs brute force parsing against all available templates, returns first match successful parsing $parseResults = $parser->parseText($textToParse); print_r($parseResults->getParsedRawData()); //slower, performs a similarity check on available templates to select the most matching template before parsing print_r( $parser ->parseText($textToParse, true) ->getParsedRawData() );
解析流程
1- 获取您想要解析的文本的一个副本。
2- 将其中的每个变化文本替换为形式为{%VariableName%}
的命名变量,如果您想匹配文本的这一部分的所有内容,或者{%VariableName:Pattern%}
,如果您想匹配一组特定的字符或使用更精确的图案。
3- 将模板文件添加到模板目录(在解析代码中定义)中,文件扩展名为txt(例如fileName.txt
)
4- 将您希望解析的文本传递给类的解析方法,让它为您完成魔法。
模板示例
如果您想要解析的文本文档看起来像这样
Hello,
If you wish to parse message coming from a website that states info like:
ID & Source: 12234432 Website Form
Name: Pet Cat
E-Mail: email@example.com
Comment: Some text goes here
Thank You,
Best Regards
Admin
您的模板文件(example_template.txt
)可能像这样
Hello,
If you wish to parse message coming from a website that states info like:
ID & Source: {%id:[0-9]+%} {%source%}
Name: {%senderName%}
E-Mail: {%senderEmail%}
Comment: {%comment%}
Thank You,
Best Regards
Admin
成功解析作业的输出将是
Array(
'id' => '12234432',
'source' => 'Website Form',
'senderName' => 'Pet Cat',
'senderEmail' => 'email@example.com',
'comment' => 'Some text goes here'
)
从v1.x升级到v2.x
版本2.0基本上是库版本1.x的重构副本,并提供完全相同的功能。只是返回结果中有一点细微差别。现在返回的是解析后的数据对象,而不是数组。要获取像v1.x那样作为数组的输出,只需在返回的对象上调用"getParsedRawData()"即可。
<?php //ParseText used to return array in 1.x $extractedArray = $parser->parseText($textToParse); //In 2.x you need to do the following if you want an array $extractedArray = $parser->parseText($textToParse)->getParsedRawData();