簡體   English   中英

在python中從文本文件讀取數字

[英]Reading numbers from a text file in python

我有一個很大的文本文件,如下所示,包括字符串和數字。 我只想讀取數字,還要刪除只有3列的行,然后將它們寫入矩陣(m×n)。 誰能告訴我python處理此類文件的最佳方法是什么?

我的文件是這樣的:

# Chunk-averaged data for fix Dens and group ave
# Timestep Number-of-chunks Total-count
# Chunk Coord1 Ncount density/number
4010000 14 1500
  1 4.323 138.758 0.00167105
  2 12.969 121.755 0.00146629
  3 21.615 127.7 0.00153788
  4 30.261 131.682 0.00158584
  5 38.907 127.525 0.00153578
  6 47.553 136.322 0.00164172
  7 56.199 118.014 0.00142124
  8 64.845 125.842 0.00151551
  9 73.491 120.684 0.00145339
  10 82.137 132.282 0.00159306
  11 90.783 121.567 0.00146402
  12 99.429 97.869 0.00117863
  13 108.075 0 0
  14 116.721 0 0......

您尚未指定矩陣的確切含義,因此這里提供了一種解決方案,它將文本文件轉換為二維列表,使每個數字都可以單獨訪問。

它檢查在給定行中的第一項是一個數字,並且存在4項的行中,在這種情況下,將追加該行作為4個獨立的數字到2D列表mat 如果要訪問mat任何數字,可以使用mat[i][j]

with open("test.txt") as f:
    content = f.readlines()

content = [x.strip() for x in content]
mat = []

for line in content:
    s = line.split(' ')
    if s[0].isdigit() and len(s) == 4:
        mat.append(s)

將樣本復制n粘貼到txt

In [350]: np.genfromtxt(txt.splitlines(), invalid_raise=False)
/usr/local/bin/ipython3:1: ConversionWarning: Some errors were detected !
    Line #2 (got 4 columns instead of 3)
    Line #3 (got 4 columns instead of 3)
  ....
  #!/usr/bin/python3
Out[350]: array([4.01e+06, 1.40e+01, 1.50e+03])

讀取了第一條非注釋行,並將其作為標准。 跳過這一點,我可以閱讀所有內容:

In [351]: np.genfromtxt(txt.splitlines(), invalid_raise=False,skip_header=4)
Out[351]: 
array([[1.00000e+00, 4.32300e+00, 1.38758e+02, 1.67105e-03],
       [2.00000e+00, 1.29690e+01, 1.21755e+02, 1.46629e-03],
       [3.00000e+00, 2.16150e+01, 1.27700e+02, 1.53788e-03],
       [4.00000e+00, 3.02610e+01, 1.31682e+02, 1.58584e-03],
       [5.00000e+00, 3.89070e+01, 1.27525e+02, 1.53578e-03],
       [6.00000e+00, 4.75530e+01, 1.36322e+02, 1.64172e-03],
       [7.00000e+00, 5.61990e+01, 1.18014e+02, 1.42124e-03],
       [8.00000e+00, 6.48450e+01, 1.25842e+02, 1.51551e-03],
       [9.00000e+00, 7.34910e+01, 1.20684e+02, 1.45339e-03],
       [1.00000e+01, 8.21370e+01, 1.32282e+02, 1.59306e-03],
       [1.10000e+01, 9.07830e+01, 1.21567e+02, 1.46402e-03],
       [1.20000e+01, 9.94290e+01, 9.78690e+01, 1.17863e-03],
       [1.30000e+01, 1.08075e+02, 0.00000e+00, 0.00000e+00],
       [1.40000e+01, 1.16721e+02, 0.00000e+00, 0.00000e+00]])

實際上,在這種情況下,其余所有部分均具有必需的4。如果我截斷了最后兩行,則會收到警告,但它仍會讀取其他行。

另一種選擇是在將行傳遞給genfromtxt之前對其進行過濾。 genfromtxt接受輸入行的任何輸入-文件,字符串列表或讀取和過濾文件的函數。

對於您的任務,您將需要迭代器,string.split()和re.match:

import re #needed to use regexp to see if line in file contains only numbers

matrix = [] #here we'll put your numbers
i = 0 #counter for matrix rows

for line in open('myfile.txt'): #that will iterate lines in file one by one
    if not re.match('[ 0-9\.]', line): #checking for symbols other than numbers in line
        continue #and skipping an iteration if there are any

    list_of_items = line.split(' ') #presumed numbers in string are divided with spaces - splittin line into list of separate strings
    if len(list_of_items) <= 3: #we will not take ro of 3 or less into matrix
        continue

    matrix.append([]) #adding row to matrix

    for an_item in list_of_items:
        matrix[i].append(float(an_item)) #converting strings and adding floats to a row
    i += 1

我試圖讓代碼和注釋說話,讓我知道是否有任何不清楚的地方

暫無
暫無

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

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