【问题标题】:how to convert newline-delimitted semi-structured data to structured如何将换行符分隔的半结构化数据转换为结构化数据
【发布时间】:2015-07-02 16:35:19
【问题描述】:

我有一个data set,其中每条记录由一个空行分隔:

P http://codeproject.com/kb/silverlight/convertsilverlightcontrol.aspx
T 2008-08-01 00:00:00
Q how to create property binding in a visual webgui silverlight control
Q videoplayer silverlight controls videoplayer videoplayer silverlight controls version 1 0 0 0 culture neutral publickeytoken null
Q videoplayer controls videoplayer videoplayer controls

P http://wallstreetexaminer.com/?p=2987
T 2008-08-01 00:00:01

P http://news.bbc.co.uk/go/rss/-/1/hi/scotland/highlands_and_islands/7535558.stm
T 2008-08-01 00:00:01
Q our continuing strategic priority is to provide a safe and efficient group of airports while pursuing development opportunities which improve the air transport network serving the region
Q our results for the year demonstrate that we have delivered against these targets and ensured that our airports have continued to play a central role in the economic and social life of the highlands and islands and tayside

P http://news.bbc.co.uk/go/rss/-/1/hi/scotland/south_of_scotland/7535392.stm
T 2008-08-01 00:00:01
Q safeguard our fishing communities birthright for future generations
Q every time i visit a fishing community in scotland i am asked to take steps to protect fishing rights for future generations

P http://news.bbc.co.uk/go/rss/-/1/hi/scotland/north_east/7535090.stm

每一行都被视为一个单独的“字段”。同一记录的某些字段出现多次。这是数据“模式”。如您所见,同一条记录中,短语或“Q”可以多次出现。

行首字母的编码位置:

  • P:文档的网址
  • T:发帖时间(时间戳)
  • Q:从文档文本中提取的短语
  • L:文档中的超链接(指向网络上其他文档的链接)

如何将此数据集转换为可以更轻松地运行聚合、分组、计数、区分、统计的形式?

理想情况下,最好将此数据集转换为 csv 或 json 格式,以便我可以使用已构建的工具(例如 bash/python/R/mongodb)进行文本挖掘/处理/自然语言处理。

【问题讨论】:

  • 他们为您记录格式。逐行阅读,并按组转换为 JSON(在空行处中断)。但是,您有一个更大的问题,因为这些文件往往是 4G+。 R 有内存限制(尽管 Python ppl 说什么,它也有)。我不确定您将在bash 中使用哪些 ML/NLP 工具。你真的需要考虑你的分析管道/架构来做你想做的事,而且你似乎陷入了“基本文本文件解析”。
  • @hrbrmstr 我感谢您的回复。您建议使用什么转换为 json?你会推荐什么架构,我不必外包给 AWS 来处理大型数据集?
  • R 或 Python(或 Perl 或 node 或任何东西)可以真的轻松地进行这种转换。但是,SO 不是编码服务,因此除非您发布您尝试过但未成功的代码,否则仅此而已。我会研究 Spark 以进行这种大规模分析(它具有 R 和 Python 的接口)。
  • 我认为缺乏努力。这可以用任何编程语言直接解决。

标签: python bash text


【解决方案1】:

以下代码获取给定格式的文件并生成 csv。同一短语的多次出现用竖线连接。

#!/usr/bin/perl -wl


my @t = qw(P T Q L);
my %h = ();

while (<>) {


    if (/^$/ .. /^$/) {

        my $r = "";

        foreach my $k (@t) {

            $r .= ',' if length($r) > 0;
            $r .= join('|', @{$h{$k}}) if exists($h{$k});           
        }

        print $r;
        %h = ();

    } else {

        if (/^([PTQL])\s+(.*)$/) {

            $h{$1} = () unless exists($h{$1});  
            push @{$h{$1}}, $2;
        }
    }
}

显然,这不是 Python 解决方案,而且方法有点幼稚,因为字段中使用的分隔符(逗号和管道)没有转义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 2017-11-26
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    相关资源
    最近更新 更多