【问题标题】:Simple command line handling equivalent of Perl in Python简单的命令行处理相当于 Python 中的 Perl
【发布时间】:2011-06-03 18:12:14
【问题描述】:

我已经完成了一些基本的 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 变量如此?

【问题讨论】:

标签: python perl command-line-arguments


【解决方案1】:
#file: process_columns.py
#!/usr/bin/python

import fileinput

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

上面的sn-p可以这样用

./process_columns.py < data

或者只是

./process_columns.py data

【讨论】:

  • 不知道fileinput 模块!不错。
【解决方案2】:

相关: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

编辑: 猜测一下,您正在读取一个字节字符串,并且必须将其正确编码为 un​​icode 字符串;执行此操作的正确方法取决于文件保存的格式以及您的本地化设置。另见Character reading from file in Python

【讨论】:

  • 我还需要 H[22] 列成为 unicode 字符。如何使 col 变量如此?
  • 不清楚你的意思是什么,但如果你在谈论 unicode 文字:docs.python.org/howto/…
  • @pbx 我需要 H[22] 列字符串为 unicode。我试着做 col = u"H[22]" 但这不起作用。我需要存储在 H[22] 中的值作为 unicode 字符。
  • @sfactor - 文件中字符的编码是什么?例如。如果是 'latin1',则使用 H[22].decode('latin1') 获取 unicode 对象
  • @sfactor 我真的认为您不了解 Unicode 是什么或它是如何工作的。请阅读joelonsoftware.com/articles/Unicode.html,然后提出一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
相关资源
最近更新 更多