【问题标题】:Reading a section of a line in a file in python 2.7在python 2.7中读取文件中的一行的一部分
【发布时间】:2019-03-04 21:06:34
【问题描述】:

我正在使用 python 2.7,因为这是我的教授让我们使用的。

我正在分析标志数据,每行包含关于每个标志的 30 个属性。

我只关心第 1 和第 11-17 属性,但不知道如何在没有其他我不关心的情况下读取和存储它们。

我对 python 也很陌生,所以这可能是一个我不知道的简单任务,所以如果有任何建议有帮助,我真的很感激。

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

文件中的一行示例:

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

【问题讨论】:

  • 您使用的是 csv 数据吗?请粘贴一些代码,向我们展示您是如何打开文件的。
  • 它可能适合,但目前在一个用逗号分隔的 txt 文件中 @DanielScott
  • 将数据拆分为数组并使用第 11 到第 17 个属性.. 如果您显示示例数据,这将对社区有所帮助
  • 从该示例行中,哪些属性将是正确的输出?因为从函数名称来看,您似乎更有可能对第 0、16、27 和 28 列感兴趣(Python 索引从零开始)。
  • 从 0 开始,正确的输出是:阿富汗,1,1,0,1,1,1,0 这些值代表我感兴趣的颜色的存在,抱歉造成混淆。 @accdias

标签: python python-2.7 file data-analysis


【解决方案1】:

为什么不试试:

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

【讨论】:

  • 该列表理解可以简化为[line_arr[0]] + [line_arr[i] for i in range(10, 17)],使其更直观...恕我直言。
  • 好建议!
【解决方案2】:

根据您的回答,我建议这样:

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])

最后,attributes 数组将拥有您期望的清除数据。

【讨论】:

  • 查看更新版本,因为我错过了前一个的缩进。
  • 他还在学习python。应该让他自己做
  • accdias 我认为您的意思是:attributes.append([data[0]] + data[10:17])
  • @DanielScott,nops。操作员告诉他,他对第 1、11-17 或 0、10-16 列感兴趣,索引从零开始,就像我们在 Python 中一样。
【解决方案3】:

如果你可以使用 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))

返回:

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

【讨论】:

  • 我不知道,但我认为字符串分割和数组切片对于正在学习的人来说似乎更容易。
  • 没问题! :-D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 2011-01-29
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
相关资源
最近更新 更多