解析 SAS 中的 HTML 数据

Parsing HTML Data in SAS

大家好,我是 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 并且对它知之甚少。

谢谢。

HTML 解析起来可能有点棘手,具体取决于您要阅读的内容。我对 HTML 只有基本的了解,但我可以识别一些模式来读入它。这就是我处理它的方式:

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

如果您想查看逻辑是如何工作的,请删除 keepif() 语句以输出所有内容 line-by-line.

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) 概念。它将真正帮助您理解数据步骤语言及其处理方式。上面有一个非常棒的社区 post here。一旦您掌握了它,您就可以在 SQL、数据步骤和过程之间跳来跳去,以编写可以处理庞大数据集的灵活程序。