![](/img/trans.png)
[英]I am trying to read a .txt file and create two new lists out of it. In python
[英]Trying to read information in a file into two lists in Python
我認為這是一個相對簡單的問題,但我是初學者並遇到麻煩。 我必須將文本文件中的信息讀入python中的兩個列表。
這是文本文件的示例,它被稱為'ratings.txt',三個列是movieId | numberofRatings | averageRatings。
1|452|3.9
2|131|3.2
3|90|3
4|209|3.6
...
...
1321|2|2.5
...
...
1685|0|-nan
1686|0|-nan
我需要將第二和第三列數字讀入兩個獨立的數組。 第二列數字需要讀入列表numRatings。 並且需要將第三列讀入avgRatings列表。 文本文件從電影1到1686
所以numRatings
需要是[452,131,90,....0,0]
而avgRating
需要是[3.9,3.2,3,....-nan,-nan]
我想我必須創建列表,然后創建循環來讀取文本文件並將這些數字存儲在數組中。
到目前為止,這是我的代碼
f = open("ratings.txt") #opens the text file
line = f.readline() #reads in one line of the file
a = line.split("|") #splits the line of the file, for example line 1 looks like [1, 452, 3.9]
在上面的代碼,如果我打印a[0]
a[1]
和a[2]
余得到1
, 452
,和3.9
分別。
如何反復執行此操作並將結果存儲到數組中?
你真的有一個CSV風格的文件,所以使用csv
模塊 :
import csv
results = []
with open('ratings.txt', 'rb') as f:
reader = csv.reader(f, delimiter='|')
for row in reader:
results.append(row)
你可以根據需要增加它; 將第二列和第三列附加到單獨的列表,將它們轉換為int
和float()
,例如:
numRatings = []
avgRating = []
with open('ratings.txt', 'rb') as f:
reader = csv.reader(f, delimiter='|')
for row in reader:
numRatings.append(int(row[1]))
avgRating.append(float(row[2]))
如果這不是 CSV樣式的文件,你仍然使用循環; 你直接在文件對象上循環:
with open('ratings.txt', 'rb') as f:
for line in f:
a = line.strip().split("|")
這樣的事情:
In [56]: with open("abc") as f:
numRatings=[]
avgRating=[]
for line in f:
f,s,t=map(float,line.split("|"))
numRatings.append(s)
avgRating.append(t)
....:
In [57]: numRatings
Out[57]: [452.0, 131.0, 90.0, 209.0]
In [58]: avgRating
Out[58]: [3.9, 3.2, 3.0, 3.6]
要么 :
In [68]: with open("abc") as f:
z=zip(*(map(float,line.split("|")) for line in f))
numRatings=z[1]
avgRating=z[2]
....:
In [69]: numRatings
Out[69]: (452.0, 131.0, 90.0, 209.0)
In [70]: avgRating
Out[70]: (3.9, 3.2, 3.0, 3.6)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.