2015-09-01 41 views
0
def loadfunc(filestr): 
listoftuples = [] 
listofnumbers = [] 
tupleinlist = [] 
with open(filestr, 'r') as file: 
    for line in file: 
     for item in line: 
      if item.isdigit(): 
       listofnumbers.append(float(item)) 
      else: 
       word = item 
tupleinlist.append(word) 
tupleinlist.append(listofnumbers) 
listoftuples.append(tuple(tupleinlist)) 
return listoftuples 
print(listoftuples) 

以上是我的代碼。所以要求將數據從.csv文件加載到元組列表中。該文件中的數據是這樣的:如何在不導入.csv模塊/庫的情況下從.csv文件加載數據

- apple 23.2 24.3 25.6 
- banana 22.1 20.0 19.9 

它必須是(word, listoffloats)列表Withing每個元組這樣的列表將如下所示:

[(apple, [23.2, 24.3, 25.6]), (banana, [22.1, 20.0, 219.9])] 

但我的代碼是螺絲這並不會返回,因爲當它遍歷每個「行」,「項」,它遍歷每個字符(如.apple),而不是像apple23.2項目是事,等

請幫助,我不知道如何解決這個問題,並且不允許在本教程中使用csv庫/模塊。

+0

不要使用'file'作爲變量名稱,要覆蓋內置'當你做file'功能這可能會造成麻煩。 – SuperBiasedMan

回答

1

比方說你有t.csv中的數據。您可以將數據保存在results列表中,然後在文件的每一行上使用split,並將分割的結果附加到results。使用csv模塊可以爲您做到這一點,但您可以使用split複製分隔符行爲。

with open('t.csv', 'r') as f: 
    results = [] 
    for line in f: 
      words = line.split(',') 
      results.append((words[0], words[1:])) 
    print results 
0

考慮到輸入文件包含輸入像

# in.txt 
# apple 23.2 24.3 25.6 
# banana 22.1 20.0 19.9 
# end 
from collections import defaultdict 

def get_word_float(infile_str): 
    d = defaultdict(list) 
    with open(infile_str) as inf: 
     for l in inf: 
      item = l.split() # split by space    
      d[item[0]].extend(map(float, item[1:])) 
    return d 

print(get_word_float('in.txt')) 

# defaultdict(<class 'list'>, {'apple': [23.2, 24.3, 25.6], 'banana': [22.1, 20.0, 19.9]}) 
0
with open('a.csv', 'r') as f: 
    #read from csv line by line, rstrip helps to remove '\n' at the end of line 
    lines = [line.rstrip() for line in f] 

results = [] 
for line in lines: 
    words = line.split(',')#get each item in one line 
    listOfFloat = map(float,words[1:])# convert string to float 
    tup = (words[0],listOfFloat) 
    results.append(tup) 
print results