简体   繁体   English

如何使用python计算csv文件中单词的出现次数?

[英]How do I count occurrences of a word in a csv file using python?

So for my assignment I was giving a csv file and am supposed to print the number of people in the file, the amount of each type of email (.jp , .uk., etc.) and print the last names in the file that show up more than once. 因此,对于我的作业,我给了一个csv文件,应该打印文件中的人数,每种电子邮件的数量(.jp,.uk。等),并在文件中打印姓氏出现不止一次。 Whenever I run the program, it says there is 0 of each email type. 每当我运行该程序时,它说每种电子邮件类型都为0。 What am I doing wrong? 我究竟做错了什么?

I thought by using 'if " " in file" it would find each one and add it to "jp". Any suggestions? 我以为使用'if'“ in file”会找到每个,并将其添加到“ jp”。有什么建议吗?

inFile = open('mydata.csv', 'r')

i = 0
jp = 0
uk = 0
de = 0

for line in inFile:
    i = i + 1
````
if '.jp' in inFile:
    jp = jp + 1
````
if '.uk' in inFile:
    uk = uk + 1
````
if '.de' in inFile:
    de = de + 1

print('There are', i - 1,'people in this file,')
print('There are', jp,'emails that end in .jp')
print('There are', uk,'emails that end in .uk')
print('There are', de,'emails that end in .de')

inFile.close()
outFile.close()

You aren't iterating across the contents of the file for your if conditions. 您无需为if条件遍历文件的内容。

for line in file:
   i = i + 1
   if '.jp' in line:
       ...
   if '.uk' in line:
       ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM