2017-04-04 68 views
0

我有一個excel文檔,我已經導出爲CSV格式。它看起來像這樣:我想爲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" 

我有一個名爲「類別」,有一個名稱變量的類。我的代碼使每個第一線串的一類,但現在我需要給每個項目添加到列,它應該是在去了。

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 

我不知道怎麼回事。這兩行代碼之間沒有任何可能會搞砸的代碼。

+0

你可以學習[如何提出一個很好的問題(http://stackoverflow.com/help/how-to-ask),並創建a [Minimal,Complete,and Verifiable](http://stackoverflow.com/help/mcve)示例。這使我們更容易幫助你。具體來說,這裏沒有數據,並且有相當多的代碼似乎與該問題沒有任何關係。 –

+0

我編輯了我的問題。希望現在它更符合標準。 –

回答

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) 
+0

完美!非常感謝! –

0

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
0

請嘗試使用以下語句閱讀csv。

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

其中數據[0]將所有類別名稱

相關問題