我需要解析实时聊天对话的文字记录。看到这个文件后,我的第一个想法是使用正则表达式来解决这个问题,但我想知道人们还使用了什么其他方法。
我在标题中添加了优雅,因为我之前发现,这种类型的任务只依靠正则表达式很难维护。
成绩单是由www.providesupport.com生成的,并通过电子邮件发送到一个帐户,然后我从电子邮件中提取一个纯文本的成绩单附件。
解析文件的原因是提取对话文本以供稍后使用,还可以识别访问者和操作员姓名,以便可以通过CRM获得信息。
下面是一个脚本文件的示例:
Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But… that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)发布于 2008-10-21 23:25:53
不,事实上,对于你描述的特定类型的任务,我怀疑有比正则表达式更“干净”的方法来完成它。看起来你的文件中嵌入了换行符,所以通常我们在这里要做的是将行作为你的分解单位,应用每行正则表达式。同时,创建一个小型状态机,并使用正则表达式匹配来触发该状态机中的转换。这样,您就知道自己在文件中的位置,以及可以预期的字符数据类型。另外,考虑使用命名捕获组并从外部文件加载正则表达式。这样,如果脚本的格式发生变化,只需调整正则表达式,而不是编写新的特定于语法分析的代码。
发布于 2008-10-22 03:01:20
对于Perl,您可以使用Parse::RecDescent
它很简单,而且您的语法稍后将可维护。
发布于 2008-10-22 00:23:33
您可能想要考虑一个完整的解析器生成器。
正则表达式很适合搜索文本中较小的子字符串,但如果您真的对将整个文件解析成有意义的数据感兴趣,那么正则表达式的功能就会很差。
如果子字符串的上下文很重要,则它们尤其不够。
大多数人对任何事情都使用正则表达式,因为这是他们所知道的。他们从来没有学习过任何解析器生成工具,他们最终编写了大量的产生式规则组合和语义操作处理,这些都是您可以通过解析器生成器免费获得的。
正则表达式很棒,但是如果你需要一个解析器,它们是无法替代的。
https://stackoverflow.com/questions/223866
复制相似问题