一:問題描述:
如下圖所示,我們要統計表格中每行數據值(例如藝術,設計,歷史是三個數據值)的個數
二:空格替換逗號
從表格中可以看到有些數據值之間是空格,有些數據值之間是逗號。我們利用excel本身有的搜索替換把逗號替換爲空格。
三:文件讀取
利用csv.reader(csvfile)進行一行一行的讀取。
with open('mooctypecount.csv','r',encoding="utf-8") as csvfile:
reader = csv.reader(csvfile)
list1 = []
for row in reader:
四:空格數量統計
判斷一個字符串str2中空格數量。因爲一個字符串中數據值的個數總比空格個數多1.
for ch in str2:
if ch.isspace():
spacesum = spacesum + 1
五:文件寫入
list1是包含衆多數值的列表。我們把列表中的數一個一個讀入csv文件的每行中。
with open("mooctypecountresult.csv", "w") as csvfile:
writer = csv.writer(csvfile)
for value in list1:
list6 = []
list6.append(value)
writer.writerows([list6])
六:統計表格中每行數據值的個數的全部源代碼
import pandas as pd
import numpy as np
import csv
with open('mooctypecount.csv','r',encoding="utf-8") as csvfile:
reader = csv.reader(csvfile)
index = 0;
list1 = []
for row in reader:
index = index +1
print(index)
str2 = ""
str2 = row[0]
spacesum = 1
#print(str2)
for ch in str2:
if ch.isspace():
spacesum = spacesum + 1
list1.append(spacesum)
#print( spacesum)
with open("mooctypecountresult.csv", "w") as csvfile:
writer = csv.writer(csvfile)
for value in list1:
list6 = []
list6.append(value)
writer.writerows([list6])
七:測試結果:
八:代碼中涉及的知識點總結
[注意]:如何遇見表格中存在空的表格單元,會影響數據分析情況。
list小結:
len(list) 可以判斷list的長度。
list[index] 得到list中某個索引值。
list.append() 把數據添加到list中。
list1 = [] 定義列表