简体   繁体   English

在 processing.py 中加载 csv 文件

[英]Load csv file in processing.py

I am trying to load a csv file in processing.py as a table.我正在尝试将 processing.py 中的 csv 文件作为表格加载。 The Java environment allows me to use the loadTable() function, however, I'm unable to find an equivalent function in the python environment. Java 环境允许我使用 loadTable() 函数,但是,我无法在 python 环境中找到等效的函数。

You can parse your csv file in an array list with this : 您可以使用以下命令解析数组列表中的csv文件:

import numpy as np
array_list = np.genfromtxt('file.csv',delimiter=';',dtype=None)

The missing functionality could be added as follows:可以按如下方式添加缺少的功能:

import csv

class Row(object):
    def __init__(self, dict_row):
        self.dict_row = dict_row

    def getFloat(self, key):
        return float(self.dict_row[key])

    def getString(self, key):
        return self.dict_row[key]

class loadTable(object):
    def __init__(self, csv_filename, header):
        with open(csv_filename, "rb") as f_input:
            csv_input = csv.DictReader(f_input)
            self.data = [Row(row) for row in csv_input]

    def rows(self):
        return self.data

This reads the csv file into memory using Python's csv.DictReader class.这使用 Python 的csv.DictReader类将 csv 文件读入内存。 This treats each row in the csv file as a dictionary.这将 csv 文件中的每一行都视为字典。 For each row, it creates an instance of a Row class which then lets you retrieve entries in the format required.对于每一行,它创建一个Row类的实例,然后您可以检索所需格式的条目。 Currently I have just coded for getFloat() and getString() (which is the default format for all csv values).目前我刚刚编码了getFloat()getString() (这是所有 csv 值的默认格式)。

You could create an empty Table object with this:您可以使用以下方法创建一个空的Table对象:

from processing.data import Table
t = Table()

And then populate it as discussed at https://discourse.processing.org/t/creating-an-empty-table-object-in-python-mode-and-some-other-hidden-data-classes/25121然后按照https://discourse.processing.org/t/creating-an-empty-table-object-in-python-mode-and-some-other-hidden-data-classes/25121 中的讨论填充它

But I think a Python Dict as proposed by @martin-evans would be nice.但我认为@martin-evans 提出的 Python 字典会很好。 You load it like this:你像这样加载它:

import csv
from codecs import open # optional to have the 'enconding="utf-8"' in Python 2

with open("data/pokemon.csv", encoding="utf-8") as f:
    data = list(csv.DictReader(f))  # a list of dicts, col-headers as keys   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM