2017-07-26 50 views
-4

蟒蛇纔有可能寫一個程序,它從一個.txt文件中讀取數據,並把這些數據轉化爲表,進行計算,等等在PYTHON中是否可以編寫一個從.txt文件讀取數據的程序?

例如,如果你有一個.txt文件那讀:

 
LINE1| 2011  18.5 11.8 19.7 31.6 26.6 37.3 37.4 24.6 34.0 71.3 46.3 28.4 

LINE2| 2012  55.2 92.0 87.5 81.0 83.5 79.6 115.1 112.7 115.7 112.7 136.2 127.4 

你能計算分配給每年的數字的平均值? (注意:我正在使用版本3.4)

+0

你有沒有在你的文本文件一號線2號線和琴絃? – Dark

+3

是的,這是可能的。 –

+0

Python文檔解釋瞭如何讀取文件以及如何拆分一條線,如何在陣列中打開它等。 https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-文件 https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects –

回答

0

您可以打開文件並讀取行,然後拆分它們並將它們轉換爲列表。你可以用numpy來計算平均值。希望下面的代碼可以幫助

import numpy as np 
text_f = open('file.txt').readlines() 
text_f.remove('\n') 
arrays= [] 
for i in text_f: 
    new = i[6:] 
    arrays.append(list(map(float, new.split()))) 
avrgs = {} 
for i in arrays: 
    avrgs[i[0]] = np.mean(i[1:]) 
avrgs 

輸出:

{2011.0: 32.291666666666664, 2012.0: 99.88333333333334} 
0

首先,你需要正確地通過剝離任何換行符或空格字符閱讀txt文件和格式:現在

with open(name.txt) as f: 
    c = f.readlines() 
c = [i.strip() for i in c] 

c = ['2011 18.5 11.8 19.7 31.6 26.6 37.3 37.4 24.6 34.0 71.3 46.3 28.4', '2012 55.2 92.0 87.5 81.0 83.5 79.6 115.1 112.7 115.7 112.7 136.2 127.4'] 

現在,你有每行到一個列表,你現在可以在列表中每個字符串中的字符串分割成一個列表,並轉換成浮動:

for i in range(len(c)): 
    c[i] = map(float, c[i].split(" ")) 

現在,我們有

c = [[2011.0, 18.5, 11.8, 19.7, 31.6, 26.6, 37.3, 37.4, 24.6, 34.0, 71.3, 46.3, 28.4], [2012.0, 55.2, 92.0, 87.5, 81.0, 83.5, 79.6, 115.1, 112.7, 115.7, 112.7, 136.2, 127.4]] 

現在,您知道c中每個子列表的第一個索引是年份。最好的數據結構來存儲這是一個字典,其中關鍵是年份,價值是平均值。

year_avg = dict() 
for arr in c: 
    year_avg[arr[0]] = sum(arr[1:])/len(arr[1:]) 

你現在有:

year_avg = {2011.0: 32.291666666666664, 2012.0: 99.88333333333334} 

僅供參考,整個代碼:

with open("file_name.txt") as f:      # Open the file 
    c = f.readlines()        # Read all the files into a variable 
c = [i.strip() for i in c]       # Format the string properly 
for i in range(len(c)): 
    c[i] = map(float, c[i].split(" "))    # Split each line into list and convert values to floats 
year_avg = dict()         # Initialize dictionary to store averages 
for arr in c:          # Iterate over the list 
    year_avg[arr[0]] = sum(arr[1:])/len(arr[1:]) # We know that the first index is the year (becomes the key) and find the average from the remaining numbers. 
print year_avg 
相關問題