菜鸟求解
我从来没有用过perl。现在有一个文件需要处理。因为项目时间太紧,估计自己学习perl后再写个程序已经来不及了,所以需求大牛们的帮助。要求如下:
我有一个文件,假设文件名为filename.txt,里面的内容大概是下面的一个形式。
<command_node keyword="alias" helpmethod="0" help="Display, add, delete alias string\r\n# alias\r\n# alias <alias name>\r\n# alias <alias name> <replaced text>\r" helphandler="" mode_support="false" prompt_string="" access_level="0" allow_no_form="false" inherit_rapidmarks="true" global_node="true" no_generate="false" meta_node="false" queue_node="false" nolink_node="false" partition="">
现在我想做如下的处理:
1. 把keyword="..."替换成keyword="",把help="..."替换成help="",并把原来的keyword和help的字符串放在按一定的格式放在另外一个文件(假设文件名为result.txt)中。result.txt文件的格式大概如下:
{"keyword string","help string"},
{...,...},
...
2. help的字符串中有一些是特殊的字符串需要被其他的字符代替。
>用>代替
<用<代替
于是上面的help字符串就被替换成下面的字符串:
Display, add, delete alias string\r\n# alias\r\n# alias <alias name>\r\n# alias <alias name> <replaced text>\r
3. 把helphandler=""替换成helphandler="help_handler_function"。
请各位大牛们给一个例子或者解答吧,万分感谢!
问题点数:100、回复次数:5Top
1 楼xyzxyz1111(程序员的自我修养)回复于 2006-03-14 14:34:34 得分 50
$/ = ">";
open(RESULT, ">result.txt");
while(<>){
s/helphandler=""/helphandler="help_handler_function"/g;
my ($kw, $hp);
if(/(keyword=")([^\"]*)"/){
$_ = "(".$`.$1."\"".$'.")";
$kw = $2;
}
if(/(help=")([^\"]*)"/){
$_ = "(".$`.$1."\"".$'.")";
$hp = $2;
}
$hp =~ s/>/>/g;
$hp =~ s/</</g;
print RESULT "[\"".$kw."\", \"".$hp. "\"]\n" if $kw or $hp;
print ;
}
close(RESULT);
Top
2 楼xyzxyz1111(程序员的自我修养)回复于 2006-03-14 14:35:43 得分 10
使用方法
perl test.pl filename.txt > filename_out.txt
Top
3 楼numchun(chunchun)回复于 2006-03-14 15:43:19 得分 0
非常谢谢xyzxyz1111。
刚才我试着运行了你给我的程序,结果基本符合我的要求。
我在提问的时候疏忽了一个细节,需要请你再帮我解决一下。
filename.txt中的内容有两种形式,如下:
<command_node keyword="alias" helpmethod="0" help="Display, add, delete alias string\r\n# alias\r\n# alias <alias name>\r\n# alias <alias name> <replaced text>\r" helphandler="" mode_support="false" prompt_string="" access_level="0" allow_no_form="false" inherit_rapidmarks="true" global_node="true" no_generate="false" meta_node="false" queue_node="false" nolink_node="false" partition="">
<pd keyword="alias name" type="string" set_rapidmark="" paramnum="0" nokeyword="yes" typename="string" validstr="" accessstr="" defaultstr="" customvalid="" convert2base="No" helpmethod="0" helpstr="alias to which the text in the <replaced text> field is bound" helphandler="" />
第一种是以command_node开头的,其helphandler=""需要用helphandler="help_handler_function"代替。
第二种是以pd开头的,其helphandler=""则保持原样。
如果这种需求,则程序应该如何修改?Top
4 楼xyzxyz1111(程序员的自我修养)回复于 2006-03-14 16:21:36 得分 40
s/helphandler=""/helphandler="help_handler_function"/g;
改成
s/helphandler=""/helphandler="help_handler_function"/g if /<command/;
就可以了Top
5 楼numchun(chunchun)回复于 2006-03-14 16:31:32 得分 0
呵呵,太感谢xyzxyz1111了。
结帖!Top




