我想把一个小Perl程序重写成Python。 我用它处理文本文件如下:
输入:
00000001;Root;;
00000002; Documents;;
00000003; oracle-advanced_plsql.zip;file;
00000004; Public;;
00000005; backup;;
00000006; 20110323-JM-F.7z.001;file;
00000007; 20110426-JM-F.7z.001;file;
00000008; 20110603-JM-F.7z.001;file;
00000009; 20110701-JM-F-via-summer_school;;
00000010; 20110701-JM-F-yyy.7z.001;file;
期望输出:
^{pr2}$以下是工作的Perl代码:
#filename: perl_regex.pl
#/usr/bin/perl -w
while(<>) {
s/^(.*?;.*?)(\w)/$1;$2/;
print $_;
}
它从命令行调用它:perl_regex.pl input.txt
Perl样式正则表达式的说明:
s/ # start search-and-replace regexp
^ # start at the beginning of this line
( # save the matched characters until ')' in $1
.*?; # go forward until finding the first semicolon
.*? # go forward until finding... (to be continued below)
)
( # save the matched characters until ')' in $2
\w # ... the next alphanumeric character.
)
/ # continue with the replace part
$1;$2 # write all characters found above, but insert a ; before $2
/ # finish the search-and-replace regexp.
有谁能告诉我,如何在Python中得到同样的结果?尤其是对于$1和$2的变量,我找不到相似的东西。在
Python正则表达式与Perl的非常相似,除了:
r'raw string literal'
。在\1
,\2
。。或者\g<1>
,\g<2>
。。在使用^{} 替换。在
python正则表达式中s/pattern/replace/的replace指令是re.sub公司(pattern,replace,string)函数,或重新编译(模式).sub(替换,字符串)。在您的情况下,您将这样做:
注意,}。对于perl,您需要按照您想要的方式迭代行(open、inputfile、splitlines…)。在
$1
变成了{相关问题 更多 >
编程相关推荐