我有一個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
我不知道怎麼回事。這兩行代碼之間沒有任何可能會搞砸的代碼。
你可以學習[如何提出一個很好的問題(http://stackoverflow.com/help/how-to-ask),並創建a [Minimal,Complete,and Verifiable](http://stackoverflow.com/help/mcve)示例。這使我們更容易幫助你。具體來說,這裏沒有數據,並且有相當多的代碼似乎與該問題沒有任何關係。 –
我編輯了我的問題。希望現在它更符合標準。 –