python或perl中的正则表达式脚本

时间:2011-03-18 08:51:30

标签: python regex perl

如果有人可以帮助我在python或perl中编写脚本,这将使我的工作更容易,在给定的文件中,它会检索所有句子,如:

[LANG::...]
  • ......意味着什么

表示例如:

[LANG::Sample text with digits 0123]

并将其以单行写入fileeach。

非常感谢你的帮助

编辑:

感谢您的帮助,现在更先进了。

如果它找到类似[:ANG :: ...]的内容,请只写...没有括号ang LANG :: tag。

谢谢你们真棒!)

4 个答案:

答案 0 :(得分:4)

import re

with open('input.txt', 'w') as f:
    text = f.read()
#text = 'Intro [LANG::First text 1] goes on [LANG::Second text 2] and finishes.'

with open('output.txt', 'w') as f:
    for match in re.findall('\[LANG::.*?\]', text):
        f.write(match+'\n')

输出:

[LANG::First text 1]
[LANG::Second text 2]

问题的第二部分如果找到类似[:ANG :: ...]的内容,请只写...没有括号和LANG :: tag。

将最后一部分更改为:

with open('output.txt', 'w') as f:
    for match in re.findall('\[.ANG::.*?\]', text):
        if match.startswith('[:ANG'):
            f.write(match[7:-1]+'\n')
        else:
            f.write(match+'\n')

根据需要修复子字符串match[7:-1]

答案 1 :(得分:4)

perl版

perl -lne "print if /\[LANG::.+?\]/;" infile > outfile

答案 2 :(得分:2)

Perl版本(编辑以从文件获取输入):

#!/usr/bin/perl 

use strict;
use warnings;

open(my $in, '<', 'input.txt');
open(my $out, '>', 'output.txt');

while ( <$in> ) {
    my @found = /\[LANG::.*?\]/g;
    print $out "$_\n" for @found;
}

答案 3 :(得分:0)

的Perl

$ perl -nE'say $1 while /\[LANG::([^]]+)\]/g' input.txt >output.txt

的Python

#!/usr/bin/env python
import fileinput, re

for line in fileinput.input():
    for match in re.findall(r'\[LANG::([^]]+)\]', line):
        print match

用法:$ print-lang input.txt >output.txt

input.txt中

井の中の蛙、大海を知らず [LANG::Japanese] a frog in a well cannot conceive 
of the ocean [LANG::English]

терпи казак, атаманом будешь [LANG::Russian] no pain, no gain [LANG::English]

output.txt的

Japanese
English
Russian
English