簡體   English   中英

如何讀取文件並將數據存儲到列表中

[英]How to read a file and store the data into a list

如果我有這種格式的文件:

1 2 3 4 5
6 7 8 9 10

在 Python 中讀取文件並將每個數字存儲到列表中的正確方法是什么?

x_table = []
for eachLine in filename_1:
#Set up temp variable
    x_table.append([])
    tmpStr = ''
#Loop through each character in the line
    for char in eachLine:
    #Check whether the char is a number
        if char.isdigit():
            tmpStr += char
        elif char == ' ' and tmpStr != '':
            x_table[eachLine].append(int(char))

我收到此錯誤:

type: list indices must be integers, not str.

閱讀每一行並使用split()將數字分成單獨的數字:

mat = []
for line in open('file.txt').readlines():
    mat.append(line.split())

之后,如果需要,您可以驗證所有行是否具有相同數量的元素。

eachLine是一個字符串(更具體地說是文檔中的一行),因此您不能將其用作x_table數組數組的索引。

你可以保持一個運行計數:

x_table = []
idx = 0
for eachLine in filename_1:
    # ...
    x_table[idx].append(int(char))
    idx += 1

編輯:或者,如果您想采用 elias 建議的方法(見下文),您可以使用列表理解來修剪不是數字的元素:

raw_mat = []
f = open('file.txt')
for line in f.readlines():
    raw_mat.append(line.split())
f.close()

mat = []
for row in raw_mat:
    mat.append([i for i in row if i.isdigit()])

如果您需要處理此函數的數字將起作用: http : //docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html除非您需要更改數組數組(數據被加載到numpy.ndarray,如果您需要數字和數學處理,這很有效)。

另一種解決方案:

如果您需要一個數組數組並且您不想更改您的核心代碼,請注意 for ... in ... 中的每個元素不是索引位置,而是實際元素。

要獲取索引位置,請執行以下操作:for i, v in enumerate(filename_1):

即便如此,如果 filename_1 是一個字符串,那也不行。 你應該在那里指定一個文件對象(它是可迭代的,並且是一行一行的)。

對於每一行 (eachLine),您可以將以下代碼附加到 x_table:

x_table.append([int(s) for s in eachLine.split()])
#eachLine.split() will break eachLine by whitespace-strings.

記得在這里捕獲異常。

完整代碼:

x_table = []
for eachLine in open(filename_1, "r"):
    x_table.append([int(k) for k in eachLine.split()])

numpy 版本的完整代碼:

import numpy
x_table = numpy.loadtxt(open(filename_1,"r").read())

記住在兩個代碼中都捕獲異常。

x_table = []
for line in filename_1:
    numbers = map(int, line.split(' '))
    x_table.append(numbers)

已搞定:

  • 多位數
  • 負數(減號)

您可以使用正則表達式。 此示例將解析小數、負數並排除文本。

"""Contents of test.txt:
1 2 3.14 4 5 0 text
6 7 -8 9 10 -99.99
some other text
1.0 0.5
"""

import re

filename_1 = open("test.txt", 'r')
values = re.findall(r"-*\d+\.*\d*", filename_1.read())

print values

請注意,這將返回一個列表。 然后,您可以將值轉換為 int 或 float。

簡單的:

file = open("myfile.dat", "r")

matrix = []
for line in file:
    matrix.append(line.split()[:])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM