我是python中的绝对初学者,我想从文本文件的第2列,第3行得到字段,如下所示:
176a AUGCACGUACGUA ACGUA AGUCU
156b GACUACAUGCAUG GCAUA AGCUA
172e AGCUCAGCUAGGC CGAGA CGACU
(文字用空格分隔)。有没有简单的方法呢?
答案 0 :(得分:0)
如果你的文件不是太大我会读它一次然后拆分每一行并获得我想要的部分:
with open(myfile) as file_in :
lines = file_in.readlines()
third_line = lines[2]
second_column = third_line.split(' ')[1]
print second_column
答案 1 :(得分:0)
您可以拆分文本并列出列表,其中每个子列表都是一行,然后使用rows[row - 1][column - 1]
从列表中选择您需要的任何内容。
f = open('test.txt', 'r')
lines = f.readlines()
f.close()
rows = []
for line in lines:
rows.append(line.split(' '))
print rows[2][1]
答案 2 :(得分:0)
如果我有一个包含您的示例数据的文件test
,则以下内容将完成此任务:
def extract_field(data, row, col):
'''extract_field -> string
`data` must be an iterable file object or an equivalent
data structure which elements contains space delimited
fields.
`row` and `col` declares the wished field position which
will be returned. '''
# cause first list element is 0
col -= 1
# jump to requested `row`
for _ in xrange(row):
line = next(data)
# create list with space delimited elements of `line`
# and return the `col`'s element of these list
return line.split()[col]
像这样使用:
>>> with open('test') as f:
... extract_field(f, row=3, col=2)
...
'AGCUCAGCUAGGC'