0
我想使用Perl来获取先前生成的SPSS语法文件并将其格式化以用于R环境。Perl正则表达式语法
对于那些熟悉Perl和正则表达式的人来说,这可能是一个非常简单的任务,但我很磕磕绊绊。
,因为我已经摆开这个Perl脚本的步骤如下:
- 读入SPSS文件
- 找到SPSS文件(正则表达式),以便进一步处理的适当块和格式化
- 上面提到的进一步处理(更多正则表达式)
- 将R语法返回到命令行或最好是文件。
SPSS值标签语法的基本格式是:
...A bunch of nonsense I do not care about...
...
Value Labels
/gender
1 "M"
2 "F"
/purpose
1 "business"
2 "vacation"
3 "tiddlywinks"
execute .
...Resume nonsense...
而且所需的R语法我的样子后:
gender <- as.factor(gender
, levels= c(1,2)
, labels= c("M","F")
)
...
这里是Perl脚本,我就此写远。我已成功将每行读入适当的数组中。我有我需要的最终打印功能的一般流程,但我需要弄清楚如何只为每个@vars数组打印适当的@levels和@labels数组。
#!/usr/bin/perl
#Need to change to read from argument in command line
open(VARVAL, "append.txt");
@lines = <VARVAL>;
close(VARVAL);
#Read through each line and put into a variable, a value, or a reject
#I really only want to read in everything between "value labels" and "execute ."
#That probably requires more regex...
foreach (@lines){
if ($_ =~ /\//){ #Anything with a/is a variable, remove the/and push
$_ =~ tr/\///d;
push(@vars, $_)
} elsif ($_ =~/\d/) {
push(@vals, $_) #Anything that has a number in the line is a value
}
}
#Splitting each @vals array into levels or labels arrays
foreach (@vals){
@values = split(/\s+/, $_); #Splitting on a space, vunerable...better to split on first non digit character?
foreach (@values) {
if ($_ =~/\d/){
push(@levels, $_);
} else {
push(@labels, $_)
}
}
}
#Get rid of newline
#I should provavly do this somewhere else?
chomp(@vars);
chomp(@levels);
chomp(@labels);
#Need to tell it when to stop adding in @levels & @labels. While loop? Hash lookup?
#Need to get rid of final comma
#Need to redirect output to a file
foreach (@vars){
print $_ ." <- as.factor(" . $_ . "\n\t, levels = c(" ;
foreach (@levels){
print $_ . ",";
}
print ")\n\t, labels = c(";
foreach(@labels){
print $_ . ",";
}
print ")\n\t)\n";
}
最后,这里是从脚本示例输出,因为它目前运行:
gender <- as.factor(gender
, levels = c(1,2,1,2,3,)
, labels = c("M","F","biz","action","tiddlywinks",)
)
我需要这不仅包括各级1,2和标签M和F
谢谢寻求帮助!
嗯,我猜就是这样简单。我需要花一些时间来消化你在那里做的事情,但我应该能够弄清楚。谢谢! – Chase 2010-07-29 00:02:42
你能解释第二个if语句在上面的代码中吗?似乎“if(length $ current_label)”将为每一行返回true,否?这是你的意图吗? 我对下一行的解释是否正确:“if($ line =〜/ ^(\ d)”(。*)“$ /)”“如果我的行以数字开头,那么抓住任何和所有字符在“”中,并将它们放在$ 1变量中? – Chase 2010-07-29 00:36:20
@Chase,它看起来像第二个“if”是为了跳过“一堆废话”行(假设它们不是以'/' )。它会阻止代码记录值,直到它找到一个有效的标签(注意'$ current_label'初始化为空字符串,它没有长度)。就我个人而言,我将'$ current_label'留下未初始化,然后测试对于定义的$ current_label代替,但是这也可以工作 – cjm 2010-07-29 01:28:46