Python一行代码提取字段

4

输入:

$ ./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

然后我尝试构建一个类似的Python单行代码,它有点起作用,但并不完美:

$ ./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'][][][]

有什么对应于Perl的Python一行代码呢?

3个回答

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
这是一个获取第一篇帖子的方法,声明你很快会有解决方案 :-) - Fredrik Pihl
我曾经拥有它,然后失去了它!现在它又回来了! - jathanism
@jathanism:这取决于你是按活跃度、最早还是投票来排序答案。 - MattH
@jathanism - 很聪明地使用了.group()!没有任何理由;只是好奇用Python写一行代码。今天学到了新东西... - Fredrik Pihl
太棒了!我很高兴能在你的学习中扮演一个角色! :) 感谢选择我的答案。 - jathanism

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

2
我正在开发一个模块, 旨在使编写Python一行代码的任务更加愉快。可以将其视为Ruby和Perl的-n-e-l-p选项,适用于Python。
$ 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接