Python中相当于Perl的简单命令行处理

-1 投票
2 回答
935 浏览
提问于 2025-04-16 09:25

我之前写过一些简单的Perl代码,但从来没有用过Python。我想在命令行中实现类似的功能,就是读取一个文件。这个文件是用制表符分隔的,所以我需要把每一列分开,然后在这些列上进行一些操作。

用Perl实现这个功能的代码是

#!/usr/bin/perl

use warnings;
use strict;

while(<>) {
    chomp;
    my @H = split /\t/;

    my $col = $H[22];

    if($H[30] eq "Good") {
       some operation in col...
    }

    else {
        do something else
    }
}

那么在Python中怎么做呢?

补充:我需要H[22]这一列是一个Unicode字符。我该怎么让col变量变成Unicode字符呢?

2 个回答

3
#file: process_columns.py
#!/usr/bin/python

import fileinput

for line in fileinput.input():
    cols = l.split('\t')
    # do something with the columns

上面的代码片段可以这样使用

./process_columns.py < data

或者直接这样

./process_columns.py data
2

相关内容: Python中与Perl的while (<>) {...}相等的用法是什么?

#!/usr/bin/env python
import fileinput

for line in fileinput.input():
    line = line.rstrip("\r\n")    # equiv of chomp
    H = line.split('\t')

    if H[30]=='Good':
        # some operation in col

        # first - what do you get from this?
        print repr(H[22])

        # second - what do you get from this?
        print unicode(H[22], "Latin-1")
    else:
        # do something else
        pass  # only necessary if no code in this section

补充说明: 我猜测你正在读取一个字节字符串,并且需要将其正确编码为Unicode字符串;具体怎么做取决于文件的保存格式以及你的本地设置。还可以查看 Python中从文件读取字符

撰写回答