用Python计数csv文件中的列 [英] counting colums in csv file with python
本文介绍了用Python计数csv文件中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想分别计算男性和女性的电子邮件帐户,因为我编写的代码无法正常工作,所以任何人都可以帮我解决这个问题这是我的代码,谢谢你
I want to count email accounts of male and female separately the code I wrote is not working properly so can anyone help me with this, please here is my code thank you in advance
import csv
mailAcc = {}
femailAcc = {}
with open('1000 Records.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for i in csv_reader:
email = i[6]
gender = i[5]
doman = email.split('@')[-1]
if doman in mailAcc:
if gender == 'm':
mailAcc[doman] = mailAcc[doman] + 1
else:
mailAcc[doman] = 1
if doman in femailAcc:
if gender == 'F':
femailAcc[doman] = femailAcc[doman] + 1
else:
femailAcc[doman] = 1
print('Mail Email accounts: ', mailAcc)
print('Femail Email Accounts: ', femailAcc)
推荐答案
以下是仅使用标准Python模块按域计算男性和女性帐户的解决方案:
Here is a solution that counts male and female accounts by domain using just standard Python modules:
import csv
from collections import Counter
males = Counter()
females = Counter()
with open('1000 Records.csv') as f:
records = csv.reader(f)
for record in records:
_, domain = record[6].split('@')
gender = record[5]
if gender.lower() == 'm':
males.update((domain.lower(),))
else:
females.update((domain.lower(),))
print('Total male accounts:', sum(males.values()))
print('Total male accounts by domain')
for k, v in males.items():
print(k, v)
print('Total female accounts:', sum(females.values()))
print('Total female accounts by domain')
for k, v in females.items():
print(k, v)
这篇关于用Python计数csv文件中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文