蟒蛇相当于到perl -pe? [英] Python equivalent to perl -pe?

查看:113
本文介绍了蟒蛇相当于到perl -pe?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要挑选一些号码的开出一些文本文件。我可以挑选出我需要使用grep行,但不知道如何从线路中提取的数字。一位同事向我展示了如何从庆典用Perl做到这一点:

I need to pick some numbers out of some text files. I can pick out the lines I need with grep, but didn't know how to extract the numbers from the lines. A colleague showed me how to do this from bash with perl:

cat results.txt | perl -pe 's/.+(\d\.\d+)\.\n/\1 /'

不过,我通常code在Python,Perl的不是。所以我的问题是,可能我也以同样的方式使用Python的?即,可我已经从管道bash的东西到Python,然后得到的结果直接到标准输出? ......如果是有道理的。或者是Perl的只是在这种情况下更方便的?

However, I usually code in Python, not Perl. So my question is, could I have used Python in the same way? I.e., could I have piped something from bash to Python and then gotten the result straight to stdout? ... if that makes sense. Or is Perl just more convenient in this case?

推荐答案

是的,你可以使用Python在命令行。 蟒蛇-c<东西> 将运行<东西> 为Python的code。例如:

Yes, you can use Python from the command line. python -c <stuff> will run <stuff> as Python code. Example:

python -c "import sys; print sys.path"

有不是直接等同于Perl的(自动输入/输出线由行处理)的 -p 选项,但是这主要是因为Python没有按'T使用 $ _ 相同的概念和诸如此类的东西是Perl那样 - 在Python中,所有输入和输出是手动完成(通过的raw_input() / 输入()打印 / 打印())。

There isn't a direct equivalent to the -p option for Perl (the automatic input/output line-by-line processing), but that's mostly because Python doesn't use the same concept of $_ and whatnot that Perl does - in Python, all input and output is done manually (via raw_input()/input(), and print/print()).

有关特定例如:

cat results.txt | python -c "import re, sys; print ''.join(re.sub(r'.+(\d\.\d+)\.\n', r'\1 ', line) for line in sys.stdin)"

(显然较为笨重,它可能会更好只是写剧本做,在实际的Python)。

(Obviously somewhat more unwieldy. It's probably better to just write the script to do it in actual Python.)

这篇关于蟒蛇相当于到perl -pe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆