5

CSV__03--使用csv库对每家店铺的所有商品评价,去掉一个最高分和一个最低分求平均值

 1 year ago
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.
neoserver,ios ssh client

python对CSV文件的读写处理常用CSV库完成。

逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。

2 前景知识

2.1 迭代器

  1. 迭代器的概念

    迭代器(iterator)有时又称光标(cursor)是程序设计的软件设计模式,可在容器对象(container,例如链表或数组)上遍访的接口。

  2. 迭代器的特点

    1. 强制性:必须将元素从迭代器中取出后,才能使用元素;
    2. 一次性:取出以后该元素就从迭代器中删除,无法二次遍历;
    3. 未知性:容器内部元素无法直接定位,只能遍历按序取出。
  3. python使用迭代器处理CSV文件

    1. 将path路径下的文件创建为reader迭代器

      reader = csv.reader(open(path, 'rt', encoding='utf-8'))
      
    2. 遍历得到迭代器全行的前四列

      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店铺的不同商品评分进行一个去掉一个最高分和一个最低分求平均值操作。

  1. 没家店铺的商品数不同;
  2. 平均分精度控制;
  3. 及时跳出循环,避免数组越界。

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK