python输入一个文件和一个字符、统计,如何打印使用Python在同一个CSV文件中的某些字符串的出现次数?...

I have a CSV file in which contains one column (column1). I want to check whether the element in cell repeats and how many times(occcurance_count).And print count of occurrence in the same CSV file using Python.

In the below example the "241682-27638-USD-OCOF" is not repeating so the count is one, "241942-37190-USD-DIV" is repeated twice so the count is 2 and so on.

Want the output as below in CSV format

column1 ,occcurance_count

1682-27638-USD-OGGCOF ,1

241682-27638-USD-OGGINT ,1

241682-27638-USD-CIGGNT ,1

241682-27638-USD-OCGGINT ,1

241942-37190-USD-GGDIV ,2

241942-37190-USD-CHYOF ,1

241942-37190-USD-EQPL ,1

241942-37190-USD-INT ,1

242066-15343-USD-CYJOF ,3

242066-15343-USD-CYJOF ,3

242066-15343-USD-CYJOF ,3

242066-15343-USD-ETHQPL ,1

242066-15343-USD-INFRT ,1

241942-37190-USD-GGDIV ,2

242066-33492-USD-CJHOF ,1

解决方案

I think below is the code which you are looking for.

logic is simple but lengthier too.

Explanation about logic:

first you need to open csv file for reading and list down all elements in list

Then use list count method to find out number of occurrence of each list item

open the new csv file and write item and count for each item.

Surely there could be optimize way of doing the same thing but here is code which comes quickly.

import csv

import sys

try :

fr = open("mycsv.csv")

fw = open("mscsv_counter.csv", "w")

except:

print "Couldn't open the file"

reader = csv.reader(fr)

counterlist = list()

for row in reader :

# print row

if len(row) > 0 :

counterlist.append(row[0])

#for item in counterlist :

# print counterlist.count(item)

writer = csv.writer(fw)

data = ["column 1", "counter"]

writer.writerow(data)

for item in counterlist :

rowdata = [item, counterlist.count(item)]

# print rowdata

writer.writerow(rowdata)

fr.close();

fw.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值