【问题标题】:I am trying to make an array for each column of a CSV file,我正在尝试为 CSV 文件的每一列创建一个数组,
【发布时间】:2017-04-04 23:49:15
【问题描述】:

我有一个已导出为 CSV 的 Excel 文档。它看起来像这样:

"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"

我有一个名为“Category”的类,它有一个名称变量。我的代码为每个第一行字符串创建了一个类别,但现在我需要将每个项目添加到它应该进入的列中。

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

我不知道出了什么问题。这两行代码之间没有任何东西可能会搞砸。

【问题讨论】:

标签: python excel csv


【解决方案1】:

问题在于您为Category 定义了类级别变量,而不是实例变量。这对

来说几乎是无害的
thisCategory.name = name
thisCategory.index = ixt

因为它为每个对象创建了实例变量来屏蔽类变量。但是

columns[index].contents.append(item)

不同。它获取单个类级别contents 列表并添加数据,而不管当时哪个实例恰好处于活动状态。

解决方案是使用在__init__ 中创建的实例变量。此外,你做了太多的工作,将东西重新组装成字符串,然后再次将它们分解。只需在读取行时处理列。

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

【讨论】:

  • 完美!非常感谢!
【解决方案2】:

3 厘米:

  1. 您没有考虑第一个字段 - 您获取一个空字符串 alltext = "" 并且您要做的第一件事就是添加一个逗号。这将所有内容都推向了一个领域。您需要测试您是否在第一行。
  2. 您正在打开一个 csv ... 然后将其转回文本文件。这看起来是因为 csv 将字段分隔值,并且您希望稍后手动执行此操作。如果您首先将文件作为文本文件打开并使用read 读取它,则不需要代码的第一部分(除非您对 csv 做了一些非常奇怪的事情;因为我们没有用于检查的样本我无法对此发表评论)。

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

将为您提供格式正确的alltext 字符串。

  1. 这是csv.DictReader 的一个很好的用例,它将为您提供结构化格式的字段。以this StackOverflow question 为例,以the documentation 为例。

【讨论】:

    【解决方案3】:

    尝试使用以下语句读取 csv。

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

    其中 data[0] 将包含所有类别名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2022-08-03
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      相关资源
      最近更新 更多