2016-12-01 24 views
0

我需要知道字符串在CSV文件中出現的次數。我擁有的代碼並沒有給我正確的編號。如何查找字符串在CSV文件中出現的次數

import csv 
import re 
def main(): 

    print('Here is the File Information.') 
    print('_' * 29) 
    infile = open('employee_payroll.csv', 'r').read() 



    count = 0 
    string = 'Board of Regents' 
    for string in infile: 
     count+= 1 
+0

請更多的細節描述... **「不給我正確的號碼」 ** ...你遠離正確的? –

+0

''Board of Regents''實際上並沒有在任何地方使用,因爲'string'的名字立即被循環變量取代;你實際上只是計算文件中的行數。另外請注意,Python有一個'csv'庫,可能會幫助你。 – jonrsharpe

回答

1

有一個.count()功能

csv = """ 
Foo, 20, Berlin 
Bar, 23, Paris 
Max, 44, New York 
Foo, 74, Sydney 
""" 

print csv.count('Foo') 
+0

什麼''FooFooFooFootbool'.count('Foo')'?這隻會計數子串,你應該指出... – dawg

1

像這樣的事情應該可以幫助解決你的問題。你可能會發現你需要試驗這些數據。數據是否有\n個字符?它是否是逗號,製表符分隔?不管下面的代碼應該如何幫助你。

count = 0 
with open(file) as f: 
    for line in f: 
     if line == 'my_word': 
      count = count + 1 
+0

SO不使用GitHub-flavored Markdown。 – jonrsharpe

+0

@jonrsharpe謝謝。 –

相關問題