【问题标题】:How to search for a word through a csv file?如何通过 csv 文件搜索单词?
【发布时间】:2018-02-25 07:39:49
【问题描述】:

这可能是一个非常简单的问题,但我是 python 新手,我已经搜索了网络但是我无法解决问题。我有一个 csv 文件,我需要在其第一行的列中搜索特定的单词。我怎样才能做到这一点?

【问题讨论】:

标签: python csv


【解决方案1】:

我使用 python 的默认 csv 模块逐行读取 csv 文件。由于您指定我们必须仅在第一行中搜索,这就是为什么我在搜索 csv 的第一行后使用 break- 来停止执行的原因。您可以删除中断,以在整个 csv 中进行搜索。希望这行得通。

import csv
a='abc'     #String that you want to search
with open("testing.csv") as f_obj:
    reader = csv.reader(f_obj, delimiter=',')
    for line in reader:      #Iterates through the rows of your csv
        print(line)          #line here refers to a row in the csv
        if a in line:      #If the string you want to search is in the row
            print("String found in first row of csv")
        break

【讨论】:

    【解决方案2】:
    import csv
    a='abc'     #String that you want to search
    with open("testing.csv") as f_obj:
        reader = csv.reader(f_obj, delimiter=',')
        for line in reader:      #Iterates through the rows of your csv
            print(line)          #line here refers to a row in the csv
            if a in str(line):      #If the string you want to search is in the row
                print("String found in first row of csv")
            break
    

    您必须添加“str(line)”才能将行转换为字符串,然后进行比较。

    【讨论】:

      猜你喜欢
      • 2017-11-13
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 2020-03-22
      相关资源
      最近更新 更多