我正在尝试为CSV文件的每一列创build一个数组,

我有一个excel文件,我已经导出为CSV。 它看起来像这样:

"First Name","Last Name","First Name","Last Name","Address","City","State" "Bob","Robertson","Roberta","Robertson","123 South Street","Salt Lake City","UT" "Leo","Smart","Carter","Smart","827 Cherry Street","Macon","GA" "Mats","Lindgren","Lucas","Lindgren","237 strawberry xing","houston","tx" 

我有一个名为“类别”,有一个名称variables的类。 我的代码为每个第一行string做了一个类别,但现在我需要将每个项目添加到它应该进入的列。

 import xlutils from difflib import SequenceMatcher from address import AddressParser, Address from nameparser import HumanName import xlrd import csv class Category: name = "" contents = [] index = 0 columns = [] alltext = "" with open('test.csv', 'rb') as csvfile: document = csv.reader(csvfile, delimiter=',', quotechar='\"') for row in document: alltext = alltext + ', '.join(row) + "\n" splitText = alltext.split('\n') categoryNames = splitText[0].split(', ') ixt = 0 for name in categoryNames: thisCategory = Category() thisCategory.name = name thisCategory.index = ixt columns.append(thisCategory) ixt = ixt + 1 for line in splitText: if(line != splitText[0] and len(line) != 0): individualItems = line.split(', ') for index, item in enumerate(individualItems): if(columns[index].index == index): print(item + " (" + str(index) + ") is being sent to " + columns[index].name) columns[index].contents.append(item) for col in columns: print("-----" + col.name + " (" + str(col.index) + ")-----") for stuff in col.contents: print(stuff) 

随着代码的运行,它为每个项目提供了一个输出:

 Bob (0) is being sent to First Name Robertson(1) is being sent to Last Name 

这是应该做的。 每个项目都说它正在被发送到正确的类别。 然而,最后,不是每个项目都属于它所要求的范畴,而是每一个范畴都有每个项目,而不是这个:

 -----First Name----- Bob Roberta Leo Carter Mats Lucas 

等等等等,每个类别。 我得到这个:

 -----First Name----- Bob Robertson Roberta Robertson 123 South Street Salt Lake City UT Leo Smart Carter Smart 827 Cherry Street Macon GA Mats Lindgren Lucas Lindgren 237 strawberry xing houston tx 

我不知道是怎么回事 这两行代码之间没有任何东西可能会搞砸了。

问题是你为Category定义了类级variables,而不是实例variables。 这对大多是无害的

 thisCategory.name = name thisCategory.index = ixt 

因为它为每个对象创build了实例variables来掩盖类variables。 但

 columns[index].contents.append(item) 

是不同的。 它获得了单个课程级别的contents列表,并添加了数据,而不pipe当时哪个实例是活动的。

解决方法是使用在__init__创build的实例variables。 而且,你做了太多的工作,将其重新组合成string,然后再打破。 只要在读取行时处理列。

 #import xlutils #from difflib import SequenceMatcher #from address import AddressParser, Address #from nameparser import HumanName #import xlrd import csv class Category: def __init__(self, index, name): self.name = name self.index = index self.contents = [] columns = [] alltext = "" with open('test.csv', 'r', newline='') as csvfile: document = csv.reader(csvfile, delimiter=',', quotechar='\"') # create categories from first row columns = [Category(index, name) for index, name in enumerate(next(document))] # add columns for the rest of the file for row in document: if row: for index, cell in enumerate(row): columns[index].contents.append(cell) for col in columns: print("-----" + col.name + " (" + str(col.index) + ")-----") for stuff in col.contents: print(stuff) 

3评论:

  1. 你没有考虑到第一个字段 – 你需要一个空stringalltext = "" ,你要做的第一件事就是添加一个逗号。 这推动了一个领域的一切。 你需要testing你是否在第一排。
  2. 你打开一个CSV文件,然后将其扭回到一个文本文件。 这看起来像是因为一个csv将字段分隔值,你想以后手动执行此操作。 如果你首先打开一个文本文件,并使用readread ,那么你不需要第一部分的代码(除非你对csv做了一些很奇怪的事情,因为我们没有一个样本审查我不能评论)。

     with open('test.csv', 'r') as f: document = f.read() 

会给你格式正确的所有alltextstring。

  1. 对于csv.DictReader ,这是一个很好的用例,它将以结构化的格式给你提供这些字段。 看到这个StackOverflow问题作为一个例子和文档 。

尝试使用下面的语句阅读csv。

 import csv data = [] with open("test.csv") as f : document = csv.reader(f) for line in document : data.append(line) 

其中数据[0]将具有所有类别名称