为什么我的输出错误在这段代码中?

时间:2016-02-14 23:44:11

标签: python csv python-3.x

我正在编写一个程序,显示有多少人根据用户输入使用特定的电子邮件提供商。我有一个CSV文件,每次运行程序时都会打印0

我的代码如下:

user = input('Enter an email'):
c=0
f_in = open('us-500.csv','r')
f_in.readline()
for line in f_in:
    line = line.strip(' ')
    first, last, company, address, city, country, state, zip, phone1, phone2, email, web = line.split(',')
    for count in email:
            if count == user:
                c +=1
print(c) 
f_in.close()

1 个答案:

答案 0 :(得分:0)

您似乎希望在各种电子邮件地址中匹配域名@example.com。这是对的吗?

如果是这样,您将不得不期望该电子邮件看起来像一个典型的地址“user@example.com”,并首先将地址分成几部分。

试试这个:

user, domain = email.split('@', 1)

此时,domain将类似于“example.com”,这对您来说已经足够了。

provider = input('Enter an email provider (like "gmail.com"): '):

count = 0
with open('us-500.csv', 'r') as users:
    users.readline()   # skip header lines
    for user in users:
        first, last, company, address, city, country, state, zip, phone1, phone2, email, web = user.split(',')
        _, domain = email.split('@', 1)
        if domain == provider:
            count += 1

print("Email provider '{}' has {} users".format(provider, count))