Simple command line handling equivalent of Perl in Python
I have done some basic Perl coding but never something in python. I would like to do the equivalent of sending the file to be read from in the command line option. This file is tab delimited, so split each column and then be able to perform some operation in those columns.
The perl code for doing this is
#!/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
}
}
What would be the python equivalent of this task?
Edit: I need the H[22] column to be a unicode character. How do I make col variable to be so?
#file: process_columns.py
#!/usr/bin/python
import fileinput
for line in fileinput.input():
cols = l.split('\t')
# do something with the columns
The snippet above can be used this way
./process_columns.py < data
or just
./process_columns.py data
Related to: Python equivalent of Perl's 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
Edit: at a guess, you are reading a byte-string and must properly encode it to a unicode string; the proper way to do this depends on what format the file is saved in and what your localization settings are. Also see Character reading from file in Python
精彩评论