如何找到csv文件中重复的字符串并用python格式化结果?

2024-05-16 05:16:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在.csv文件中有一个包含ht的文件:

1,winter
2,autumn
3,winter
4,spring
5,summer
6,autumn
7,autumn
8,summer
9,spring
10,spring

我需要解析此文件以生成包含以下内容的文件:

winter = 1,3
autumn = 2,6,7
spring = 4,9,10
summer = 5,8

我发现这篇文章How to print count of occourance of some string in the same CSV file using Python?但我不能适应我想要的。你知道吗

我感谢任何帮助或指导来解决这个问题。你知道吗

谢谢。你知道吗


Tags: 文件ofcsvtocountsomehowht
1条回答
网友
1楼 · 发布于 2024-05-16 05:16:45

创建一个空的dict,打开csv并读取每一行。
在读取每一行时,检查dict中的row[1]
否则将其添加到dict中,创建一个值为row[0]的列表。 如果已经存在,则将值附加到dict中。
像这样的。你知道吗

import csv
try :
    fr = open("mycsv.csv")
except:
    print "Couldn't open the file"
reader = csv.reader(fr)
base={}
for row in reader :
     if len(row) > 0:
            if row[1] in base: #Check if that season is in dict.
                    base[row[1]].append(row[0]) # If so add the number to the list already there.
            else:
                    base[row[1]]=[row[0]] # Else create new list and add the number
print base  

它的输出是这样的。
{'autumn': ['2', '6', '7'], 'spring': ['4', '9', '10'], 'winter': ['1', '3'], 'summer': ['5', '8']}

相关问题 更多 >