【问题标题】:How do you search for a specific word in a csv column using csv module如何使用 csv 模块在 csv 列中搜索特定单词
【发布时间】:2020-01-23 05:56:28
【问题描述】:

我有一个 csv 文件,我想从中搜索仅一列的文本。例如。如果我在“The quick brown fox jumps over the lazy dog”列中有一行文本,并且我在“text”列中搜索“dog”,我应该打印该行。到目前为止,这是我一直在努力改进的地方。

def read(option, searchitem):
    if option == "text":
        csvfile=open('myfile.csv','r')
        for row in csvfile:
            if row[2].find(searchitem):
                print(row)

但是我文件中的所有行都被打印出来了。我曾尝试浏览类似的问题并应用它们,但无济于事。

【问题讨论】:

    标签: python python-3.x csv


    【解决方案1】:

    find()如果找到匹配字符串中的索引,则返回,否则返回-1。在 Python 中,正数和负数都被视为 True0 是唯一被视为 False 的数字。因此,any_string.find(anyItem) 将始终评估为 True(因此您的所有行都被打印)。

    要检查另一个字符串中是否存在子字符串(或等于它),您可以使用in 运算符:

    if searchitem in row[2]:
        print(row)
    

    【讨论】:

    • 哦,非常感谢。这就是为什么我之前的解决方案不起作用的原因。
    【解决方案2】:

    我使用 Oliver 的建议来改进我之前的解决方案并获得了预期的结果。

    def 读取(选项,搜索项): 使用 open('text.csv', 'r') 作为 csvfile:

        # get number of columns
        for line in csvfile.readlines():
            array = line.split(',')
            first_item = array[0]
    
        num_columns = len(array)
        csvfile.seek(0)
    
        reader = csv.reader(csvfile)
        included_cols = [4]
    
        for row in reader:
            content = list(row[i] for i in included_cols)
            for item in content:
                if searchitem in item:
                    print(row)
    

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 2013-05-06
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      相关资源
      最近更新 更多