【python--读取csv文件统计店铺有关信息】

作者 :“码上有前”
文章简介 :Python
欢迎小伙伴们 点赞、收藏⭐、留言

【python--读取csv文件统计店铺有关信息】_第1张图片

python练习题

  • 读取csv文件统计店铺有关信息

读取csv文件统计店铺有关信息

import csv
import os



def get_top_store(folder_path):
    data_dict = {}  # 存储数据的字典

    # 遍历文件夹中的每个CSV文件
    for filename in os.listdir(folder_path):
        if filename.endswith(".csv"):
            file_path = os.path.join(folder_path, filename)

            # 打开CSV文件
            with open(file_path, "r",encoding="utf-8") as file:
                csv_reader = csv.DictReader(file)

                # 读取每一行数据
                for row in csv_reader:
                    try:
                        pcommit_value = row["pcommit"]
                        store_value = row["店铺"]
                        price_value = row["\ufeff价格"]
                        
                        # 将pcommit作为键,store作为字符串值存储到字典中
                        data_dict.setdefault(pcommit_value, []).append((store_value,price_value))
                    except KeyError:
                        # 跳过没有所需键的行
                        continue

    # 对字典按键(pcommit)进行由高到低的排序
    sorted_dict = dict(sorted(data_dict.items(), key=lambda x: float(x[0]), reverse=True))
    top_store = list(sorted_dict.items())[:4]
    # print("top_store===",top_store)
    # print("len",len(top_store))
    return top_store

folder_path = "./Cosmetic_data/Brand_Classification/brand&details_analysis"  
result = get_top_store(folder_path)


# 获取最火爆的四个店铺
def store_list_values(result):
    store_list = [result[0][1][0][0],result[1][1][0][0],result[2][1][0][0],result[3][1][0][0]]
    # print("store_list==",store_list_values)
    return store_list

store_list = store_list_values(result)
# print(store_list)

# 获取最火爆的销售的商品价格
def price_list_values(result):
    price_list = [result[0][1][0][1],result[1][1][0][1],result[2][1][0][1],result[3][1][0][1]]
    return price_list
# print(price_list_values(result))

你可能感兴趣的:(Python,python,开发语言)