通过命令行参数提取列数据的Python程序?

我的python程序extract.py试图从文本文件中提取“列”数据(使用命令行参数指示从中提取数据的列)。

例如; animals.txt包含...

鸟狗猫鸽子

老虎狮子青蛙

豹猴子大猩猩猿


在命令行中...

python extract.py 1 animals.txt

用于提取鸟类,老虎,豹子(数据的第一列)。

python extract.py 3 animals.txt

用于提取鸽子,青蛙,猿(数据的第三列)。


我的extract.py当前包含

import sys

file_name = sys.argv[2] # Text file input is stored in file_name

with open(file_name, "r") as my_file:
    contents = my_file.readlines()
    print(contents)

具体来说,我正在努力分别根据参数1、2、3提取列数据(第一列,第二列,第三列)

知道一行中的每个单词都由文本文件中的一个空格分隔可能会有所帮助

为协助喝彩。

PunyCode
import sys

file_name = sys.argv[2]        # Text file input is stored in file_name
col_numbr = int( sys.argv[1] ) # column number

with open(file_name, "r") as my_file:
    for each_line in my_file:            # taking line by line

        line_list = each_line.split(' ') # each line is splited at space 
                                         # and made into a list

        print ( line_list[col_numbr-1] ) # -1 is added to start indexing from 1

试试这个代码。

文本文件中的每个字符都很重要,因此不应有任何胭脂空格或换行符。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章