简体   繁体   English

在python 2.7中读取文件中一行的一部分

[英]Reading a section of a line in a file in python 2.7

I am using python 2.7 because that is what my professor is having us use. 我正在使用python 2.7,因为那是我的教授正在使用的。

I am analyzing flag data and each line contains 30 attributes about each flag. 我正在分析标志数据,每行包含有关每个标志的30个属性。

I am only concerned with the 1st and 11th-17th attributes, but am not sure how to read those in and store them without the other ones I am not concerned with. 我只关心1st和11th-17th属性,但是不确定如何读取这些属性并将其存储,而没有其他我不关心的属性。

I am also pretty new to python so this could be a simple task I am just unaware of so if any suggestions help, I really appreciate it. 我对python还是很陌生,所以这可能是一个简单的任务,我只是不知道,所以如果有任何建议可以帮助的话,我非常感谢。

def getColors():
    f = open('flag.data.txt')

An example of one line in the file: 文件中一行的示例:

Afghanistan,5,1,648,16,10,2,0,3,5,1,1,0,1,1,1,0,green,0,0,0,0,1,0,0,1,0,0,black,green

Why not try: 为什么不尝试:

def getColors():
    arr=[]
    f = open('flag.data.txt','r')
    for line in f: 
        line_arr = line.split(',')
        arr.append([line_arr[0]] + [line_arr[i] for i in range(10, 17)])
    return arr

Based on your answers, I would suggest something like this so: 根据您的回答,我建议这样:

from __future__ import with_statement

attributes = []
with open('flag.data.txt','r') as f:
    for line in f: 
        data = line.strip().split(',')
        attributes.append([data[0]] + data[10:17])

In the end, attributes array will have the cleaned out data you expect. 最后, attributes数组将具有您期望的清除数据。

If you can use numpy, np.loadtxt can be handy for problems like these: 如果可以使用numpy,则np.loadtxt可以解决以下问题:

import numpy as np 
from StringIO import StringIO

data = """Afghanistan,5,1,648,16,10,2,0,3,5,1,1,0,1,1,1,0,green,0,0,0,0,1,0,0,1,0,0,black,green"""

result =  np.loadtxt(StringIO(data),dtype=str,delimiter=',',usecols=(0,10,11,12,13,14,15,16))

returns: 返回:

array(['Afghanistan', '1', '1', '0', '1', '1', '1', '0'], dtype='|S11')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM