如何在不导入.csv模块/库的情况下从.csv文件加载数据

2024-10-01 15:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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文件加载数据并将其加载到元组列表中。文件中的数据类似于:

 - apple    23.2    24.3    25.6
 - banana   22.1    20.0    19.9

对于列表中的每个元组,它必须是(word, listoffloats),这样列表看起来像:

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

但是在我的代码中,它会把这个搞砸而不返回它,因为当它在每个“行”中遍历“item”时,它会遍历每个字符(比如.apple),而不是像apple23.2这样的项

请帮助我不知道如何解决这个问题,不,不允许在本教程中使用csv库/模块。


Tags: csv代码inapple列表forlineitem
3条回答

考虑到输入文件包含如下输入

# 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]})

假设您在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
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

相关问题 更多 >

    热门问题