Python 通过命令行参数提取列数据的程序?
Python program that extracts column data by command line arguments?
我的 python 程序 extract.py 正在尝试从文本文件中提取 "column" 数据(使用命令行参数来指示哪一列从中提取数据)。
例如; 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。
在文本文件.
中,一行中的每个单词仅由一个 space 分隔可能会有所帮助
求助干杯。
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
试试这个代码。
文本文件中的每个字符都很重要,因此不应有任何红色空格或换行符。
我的 python 程序 extract.py 正在尝试从文本文件中提取 "column" 数据(使用命令行参数来指示哪一列从中提取数据)。
例如; 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。
在文本文件.
中,一行中的每个单词仅由一个 space 分隔可能会有所帮助求助干杯。
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
试试这个代码。
文本文件中的每个字符都很重要,因此不应有任何红色空格或换行符。