CSV__03--使用csv库对每家店铺的所有商品评价,去掉一个最高分和一个最低分求平均值
source link: https://blog.51cto.com/husheng/5906902
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
python对CSV文件的读写处理常用CSV库完成。
逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。
2 前景知识
2.1 迭代器
-
迭代器的概念
迭代器(iterator)有时又称光标(cursor)是程序设计的软件设计模式,可在容器对象(container,例如链表或数组)上遍访的接口。
-
迭代器的特点
- 强制性:必须将元素从迭代器中取出后,才能使用元素;
- 一次性:取出以后该元素就从迭代器中删除,无法二次遍历;
- 未知性:容器内部元素无法直接定位,只能遍历按序取出。
-
python使用迭代器处理CSV文件
-
将path路径下的文件创建为reader迭代器
reader = csv.reader(open(path, 'rt', encoding='utf-8'))
-
遍历得到迭代器全行的前四列
column1 = [row1[0:4] for row1 in reader]
-
2.2 去掉最大值和最小值
先按照店铺workID将grade添加至temp数组
temp.remove(min(temp))
temp.remove(max(temp))
3 问题描述
有很多数据存储在csv文件中,每个店铺有唯一userID,每件商品有唯一的workID,以及评分字段,csv文件按照userID排列,需要将相同userID店铺的不同商品评分进行一个去掉一个最高分和一个最低分求平均值操作。
- 没家店铺的商品数不同;
- 平均分精度控制;
- 及时跳出循环,避免数组越界。
4 完整代码
# 对每家店铺的所有商品评价,去掉一个最高分和一个最低分求平均值
def total_work(path):
reader = csv.reader(open(path, 'rt', encoding='utf-8'))
column1 = [row1[0:4] for row1 in reader]
print("共有" + str(reader.line_num - 1) + "件作品。")
i = 1
with open("total_"+path, 'w', encoding='UTF8', newline='') as f1:
writer1 = csv.writer(f1)
writer1.writerow(["realname", "userID", "grade", "num"]) # 写入标题
while i <= reader.line_num - 1:
# 作品数
j = 1
# 得分
grade = 0
# 所有作品得分的数组
temp = [float(column1[i][3])]
while column1[i][1] == column1[i + 1][1]: # 判断userID店铺是否相同
i = i + 1
temp.append(float(column1[i][3]))
j = j + 1
# 数组中添加统一参赛者的作品得分
if i == reader.line_num - 1: # 判断是否为最后一个商品评价
break
# 去掉最小值 去掉最大值 求平均
temp.remove(min(temp))
temp.remove(max(temp))
grade = "%.3f"%(sum(temp)/(j-2))
# grade = round(temp/(j),5)
# 写入平均分
column1[i][2] = grade
# 写入作品数量
# column1[i].append(j)
column1[i][3] = j
# 存入csv
writer1.writerow(column1[i])
i = i + 1
Recommend
-
149
三大外卖平台被起诉污染:每家日耗1950万双筷子 8月24日,北京建外soho东区办公楼,楼层内的垃圾投放间堆着大量外卖垃圾。新京报记者 侯少卿 摄9月1日,北...
-
76
中新网客户端北京1月26日电(记者宋宇晟)近日,电影《纯洁心灵·逐梦演艺圈》导演毕志飞在微博发文称,因影片遭遇豆瓣史上最低分2.0一事,电影出品方已正式起诉豆瓣公司,包括索赔1元及要求判令被告公开说明情况等。对此,豆瓣方面向中新网记者回应称
-
101
国产电影《纯洁心灵》在豆瓣的评分只有2.1分(3.4万人评价,98.8%的人打一星),这也是目前豆瓣史上被评分最低的一部电影。去年9月上映的电影《纯洁心灵》仅公映3天,就因豆瓣2.0的评分过低,从全国各大院线撤下。
-
20
写在前面:本文作者为EOS创始人Daniel Larimer。他在文章中分析了传统互联网中的数据库等基础架构和设计的缺陷并指出区块链是最好的解决方案:诸如EOSIO之类的区块链开放式框架使得开发者无需为了构建安全的应用程序而重新创建“数据库”,...
-
36
民航局:国内每家航空公司经营至任一国家的航线只能保留1条
-
9
元年低代码平台:“买不来”的数字化转型,每家的“乐高”都不同 - IT业界_CIO时代网 - CIO时代—新技术、新商业、新管理元年低代码平台:“买不来”的数字化转型,每家的“乐高”都不同 2021-09-13 18:07:18 来源: ...
-
10
谷泰微CEO看2022:市场将考验每家公司的产品定义、设计、供应和技术支持能力-基础器件-与非网 ...
-
7
每家上市公司董事长,都有一颗离婚的心? • 2023-04-06...
-
4
阿里云将开放通义千问:为每家企业打造专属GPT! 2023-04-11 12:16 出处/作者:快科技 整合编辑:佚名 0
-
0
亚马逊张孝峰:游戏业的AIGC工业化,每家公司都该有可控生产线! 2023-05-18 •
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK