fpc : 连续2个以上的空格替换成1个空格

来源:互联网 发布:手机淘宝账户怎么注册 编辑:程序博客网 时间:2024/04/29 04:04

我们先看看 python 的写法: 

space1.py

# -*- coding: cp936 -*-import os, sysimport reif len(sys.argv) ==2:    f1 = sys.argv[1]else:    print 'usage: space1.py file1.txt '    sys.exit(1)if not os.path.exists(f1):    print 'ERROR: %s not found\n' % f1    sys.exit(1)fp = open(f1,'rt')f2 = f1 +'.bak'fp2 = open(f2,'w')aline =''for line in fp:    aline = re.sub(r'[ ]{2,}',' ',line)    fp2.write(aline)#fp.close()fp2.close()

我们看看free pascal 写法:

space1.pas

Program space1;{$mode objfpc}{$H+}uses sysutils;Var  f1,f2:text;  str,str2:string;  ln:integer;Begin  if ParamCount =1 then    beginAssignFile(f1,ParamStr(1));AssignFile(f2,ParamStr(1)+'.bak');    end  else beginif ParamCount =2 then  begin  Assign(f1,ParamStr(1));  Assign(f2,ParamStr(2));  end    else begin  writeln(' usage: readfile file1.txt ');  writeln(' usage: readfile file1.txt file2.bak ');  exit;end;  end;  ln:=0;  Reset(f1);  Rewrite(f2);  while not eof(f1) do  beginln:=ln+1;readln(f1,str);if length(str)>0 thenbegin  while Pos('  ',str)>0 do  begin    str := StringReplace(str,'  ',' ',[rfReplaceAll]);  end;  str2 := str;  writeln(f2,str2);    end;  end;  CloseFile(f2);  CloseFile(f1);  writeln('line number: ',ln);End.

编译 fpc space1.pas

运行 space1.exe  tmp.txt



0 0
原创粉丝点击