在SAS中解析HTML数据

问题描述 投票:0回答:1

[嗨,我是R用户,这是我第一次尝试在SAS中解析HTML数据。我能够在文本文件中获取信息,然后使用下面的行读取文件,但是我无法解析数据:

filename src "D:\testwebpage.txt";
proc http
 method="GET"
 url="xxxxx/yyyyyy"
 out=src;
run;

data rep;
infile src length=len lrecl=32767;
input line $varying32767. len;
line = strip(line);
if len>0;
run;

“ rep”中的数据如下:

<html><body style='font-family:arial'><style type="text/css">tr.head {

background-color: #FFFFFF;

font-weight: bold;

}

tr.even {background-color: #EEEEEE}

tr.odd {background-color: #FFFFFF}</style><table><tr class="head"><td>station_no</td><td>ts_path</td><td>parametertype_name</td></tr>

<tr class="even"><td>23349</td><td>17/23349/path1</td><td>WL</td></tr>

<tr class="odd"><td>23349</td><td>17/23349/path2</td><td>WL</td></tr>

<tr class="even"><td>23349</td><td>17/23349/path3</td><td>WL</td></tr>

<tr class="odd"><td>23349</td><td>17/23349/path4</td><td>WL</td></tr>

<tr><th colspan="3"><img src="images/path.gif" align="right"/>

</th></tr>

</table>

</body></html>

我需要解析“ rep”并获取一个数据集,其中包含station_no(在这种情况下为23349),ts_path(17/23349 / path1 ....)和parametertype_name(WL)。有人可以帮我吗?就像我说的,我不使用SAS,对此了解甚少。

谢谢。

sas html-parsing
1个回答
0
投票

HTML可能很难解析,具体取决于您要阅读的内容。我对HTML只是一个基本的了解,但是我可以确定一些模式来读取它。这就是我的处理方式:

  • 删除HTML标记,并使用PERL正则表达式将它们替换为空格
  • 通过查看HTML中的表格标题行是否包含关键字来进行检查。在这种情况下,我使用了station_no
  • 如果上一行是标题行,并且在删除HTML标签后该行没有丢失,那么我们当前在数据行中
  • 使用scan()获取我们需要的每个值

如果想了解逻辑的工作原理,请删除keepif()语句以逐行输出所有内容。

data rep;
    infile src length=len lrecl=32767;
    input line $varying32767. len;

    line        = strip(line);

    /* PERL regular expression to remove HTML tags.
       compbl() changes multiple spaces into one space
    */
    line_notags = compbl(prxchange('s/<[^>]*>/ /', -1, line));

    if(len>0);

    /* Do not reset these values at the start of each row */
    retain flag_table_header lag_flag_table_header;

    /* Set a flag that we've encountered the table header */
    if(index(line, 'station_no')) then flag_table_header = 1;

    /* Check if we are currently under the table header */
    lag_flag_table_header = lag(flag_table_header);

    /* If we're under the table header and the line isn't missing after removing tags,
       grab what we need and output. Do not output if anything else is missing.
    */
    if(lag_flag_table_header AND NOT missing(line_notags) ) then do;
        station_no         = scan(line_notags, 1);
        ts_path            = scan(line_notags, 2);
        parametertype_name = scan(line_notags, 3);

        output;
    end;

    keep station_no ts_path parametertype_name;
run;

SAS数据步骤语言要记住的最大事情是它是一种固有的循环语言。您编写的程序对数据集的每一行执行所有操作。每次程序单击run语句时,SAS都会转到新行,并将所有列重置为丢失,以准备读取另一行。您可以使用retain语句允许列在两次读取之间保留。

[熟悉程序数据向量(PDV)概念。它确实可以帮助您理解数据步骤语言及其处理方式。有一个非常不错的社区发布了here。一旦掌握了它,就可以在SQL,数据步骤和proc之间跳动,以编写可以处理巨大数据集的灵活程序。

© www.soinside.com 2019 - 2024. All rights reserved.