【发布时间】:2018-11-12 22:51:39
【问题描述】:
我正在尝试计算某个单词在 csv 文件中出现的次数。
import csv
path = r'C:\Users\Ahmed Ismail Khalid\Desktop\test.csv'
str = "line"
count = 0
with open(path,'rt',encoding="utf-8") as f :
reader = csv.reader(f)
for row in reader :
print(row)
if str == row[0] :
count = count + 1
print("\n \n The count is :",count)
每当我运行代码时,我总是得到输出 0 来计数。但是,所有行都被打印出来。我的 csv 文件有两列,id 和 text,数据如下:
id text
1 this is line 1
2 this is line 2
3 this is line 3
4 this is line 4
你可以看到所有的行都包含 str 并且计数应该是 4 但它总是打印为 0。
任何帮助将不胜感激。
谢谢
【问题讨论】:
-
有一个意图错误:
count = count + 1 -
我认为应该是'if str == row[1]'
标签: python csv if-statement conditional-statements