2011-09-09 23 views
4

輸入:Python中的一行提取場

$ ./ffmpeg -i test020.3gp                            
ffmpeg version UNKNOWN, Copyright (c) 2000-2011 the FFmpeg developers 
    built on May 5 2011 14:30:25 with gcc 4.4.3 
    configuration: 
    libavutil 51. 2. 0/51. 2. 0 
    libavcodec 53. 3. 0/53. 3. 0 
    libavformat 53. 0. 3/53. 0. 3 
    libavdevice 53. 0. 0/53. 0. 0 
    libavfilter 2. 4. 0/2. 4. 0 
    libswscale 0. 14. 0/0. 14. 0 
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'test020.3gp': 
    Metadata: 
    major_brand  : 3gp4 
    minor_version : 512 
    compatible_brands: 3gp4 
    creation_time : 2004-07-01 09:59:21 
    Duration: 00:01:02.20, start: 0.000000, bitrate: 284 kb/s 
    Stream #0.0(und): Audio: aac, 44100 Hz, stereo, s16, 96 kb/s 
    Metadata: 
     creation_time : 2004-07-01 09:59:21 
    Stream #0.1(und): Video: mpeg4, yuv420p, 176x120 [PAR 1:1 DAR 22:15], 184 kb/s, 15 fps, 15 tbr, 30k tbn, 15 tbc 
    Metadata: 
     creation_time : 2004-07-01 09:59:23 
At least one output file must be specified 

比方說,我想用下面的正則表達式提取寬度&高度:

(\d+x\d+) 

使用perl,我會做做這樣的事情:

$ ./ffmpeg -i test020.3gp 2>&1 | perl -lane 'print $1 if /(\d+x\d+)/' 
176x120 

然後,我試圖構建一個類似的蟒蛇單行,它有點作品,但不完美:

$ ./ffmpeg -i test020.3gp 2>&1 | python -c "import sys,re;[sys.stdout.write(str(re.findall(r'(\d+x\d+)', line))) for line in sys.stdin]" 
[][][][][][][][][][][][][][][][][][][]['176x120'][][][] 

什麼python單線看起來像對應於perl之一?

回答

5

你想要的是re.search而不是re.findall

這是卓有成效的,即使一個班輪本身是有點「醜」(/tmp/p就是你給樣本數據):

% cat /tmp/p 2>&1 | python -c "import re,sys; print re.search(r'(\d+x\d+)', sys.stdin.read()).group()" 
176x120 

你不只是使用grep任何原因(在這種情況下爲egrep)?

% cat /tmp/p | egrep -o '[0-9]+x[0-9]+' 
176x120 
+3

這是一種方式得到的第一篇文章,說你*很快*將有一個解決方案:-) –

+0

我有它,然後我失去了它!現在它回來了! – jathanism

+0

@jathanism:這將取決於你是否按活躍,最老或投票排序答案。 – MattH

2
cat sample.txt | python -c "import sys,re; print '\n'.join(re.findall(r'(\d+x\d+)',sys.stdin.read()))" 
176x120 
2

我有一個module in the works是嘗試編寫Python單行更愉快的任務。可以把它看作Python的Python和Perl的-n-e,-l,-p選項。

$ pip install oneliner 
# use as pyl-$major-$minor <args> or python -m oneliner <args> 

$ pyl-2.7 -j -ne 're.findall("\d+x\d+", line)' < ffmpeg.txt