本文介绍了如何在不导入.csv模块/库的情况下从.csv文件加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Above is my code. So the requirement is to load data from a .csv file and into a list of tuples. The data in the file is something like:

 - apple    23.2    24.3    25.6
 - banana   22.1    20.0    19.9

列表中的每个元组必须为(单词,listoffloats),因此列表看起来像:

Withing each tuple in the list it has to be (word, listoffloats) so the list would look like:

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

但是用我的代码,它解决了这个问题,并且没有返回它,因为当它遍历每行中的"item"时,它遍历每个字符(例如.a p p l e ),而不是像这样的项目>苹果 23.2

But with my code it screws this up and doesn't return it because when it iterates over "item" in each "line", it iterates over each character (like ., a, p, p, l, e) rather than item being things like apple, 23.2, etc.

请帮助,我不知道如何解决此问题,不,本教程不允许使用csv库/模块.

Help please I don't know how to fix this and no it is not allowed to use csv libraries/modules for this tutorial.

推荐答案

假设您在t.csv中有数据.您可以将数据保存在列表中,然后在文件的每一行上使用,然后将拆分结果附加到结果中.使用csv模块可以为您完成此操作,但是您可以使用 split 复制定界符行为.

Lets say you have the data in t.csv. You can hold the data in a results list, then use split on each line in the file and append the results of your split to results. Using the csv module would have done this for you, but you can replicate the delimiter behaviour with split.

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

这篇关于如何在不导入.csv模块/库的情况下从.csv文件加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:16