对于那些熟悉Perl和regex的人来说,这可能是一个非常简单的任务,但是我有点结结巴巴。
我为这个Perl脚本列出的步骤如下:
-
-
找到合适的SPSS文件块(regex)进行进一步的处理和格式化
-
-
将R语法返回到命令行,最好是返回一个文件。
...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...
gender <- as.factor(gender
, levels= c(1,2)
, labels= c("M","F")
)
...
这是我迄今为止编写的Perl脚本。我已经成功地将每一行读入适当的数组。我有最终print函数所需的一般流程,但是我需要弄清楚如何只为每个@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",)
)