一:问题描述:
如下图所示,我们要统计表格中每行数据值(例如艺术,设计,历史是三个数据值)的个数
二:空格替换逗号
从表格中可以看到有些数据值之间是空格,有些数据值之间是逗号。我们利用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 = [] 定义列表