【问题标题】:Python if statement wont execute for csvPython if 语句不会为 csv 执行
【发布时间】: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


【解决方案1】:

在打开 csv 文件时准确指定 'newline' 、 'delimiter' 和 'quote char' 以获得您想要的结果。请看下面的例子:

>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

【讨论】:

    【解决方案2】:
    import csv
    
    count = 0
    find = 'line'
    
    with open('test.csv', 'rt', encoding='utf-8') as f:
        reader = csv.reader(f)
        for row in reader:
            line = ', '.join(row)
            if find in line:
                count = count + 1
    
    print('The count is :', count)
    

    仅供参考:如果要计算单词在文件中出现的次数,可以避免加入。只需在没有 csv 模块的情况下逐行读取文件。

    【讨论】:

    • 感谢这工作。但是,没有 csv 模块的阅读是什么意思?将文件视为文本文件?
    【解决方案3】:

    使用in 查找您的字符串。

    例如:

    with open(path,'rt',encoding="utf-8") as f :
        reader = csv.reader(f)
        for row in reader :
           print(row)
           if str in row[1] :
               count = count + 1
    

    根据评论编辑

    import csv
    checkStr = 'line'
    result = []
    with open(path,'rt',encoding="utf-8") as f :
        reader = csv.reader(f)
        for row in reader :
           if checkStr not in row[1]:    #Check if 'line' not in row
               result.append(row)
    
    with open(filename,'w') as f:        #Write new result. 
        writer = csv.writer(f)
        for row in result:
            writer.writerow(row)
    
    • 附加所有没有checkStr 的行
    • 将结果写入新文件。

    【讨论】:

    • 试过了,但错误仍然存​​在。仍然计数为 0
    • 更新了 sn-p 使用 row[1]
    • 请接受对您有帮助的回答之一。谢谢
    • 知道如何删除包含 str 的整行吗?这会很有帮助,肯定会让我免于启动另一个线程
    • 更新了 sn-p。请检查。
    猜你喜欢
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多