【问题标题】:Using Python to parse CSV to find specific string使用 Python 解析 CSV 以查找特定字符串
【发布时间】:2019-01-15 16:48:45
【问题描述】:

对 python(和编程)完全陌生。 尝试编写一个读取 CSV 文件并搜索特定字符串的 python 脚本。该字符串表示一个实例,该实例最终将有助于更大的脚本(执行附加任务)。使用下面的脚本,我可以读取 CSV,但我不知道如何让脚本查找特定字符串:

import csv
with open('XXXXXXX.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for line in csv_reader:
        print(line)

我尝试过使用拆分、追加、熊猫和其他选项,但我无法让它工作。非常感谢任何帮助。

【问题讨论】:

  • 请发一个完整可执行的例子
  • 您的 .csv 文件样本会有所帮助。一般来说,用 pandas 加载它并寻找字符串应该很简单。
  • 请提供一些示例数据和所需的输出。

标签: python python-3.x csv scripting


【解决方案1】:

in 运算符可以帮助您确定某物是否在另一物中,如下所示:

for line in file:
    if "desired string" in line:
        print("It's here")

IDLE 中的一些示例:

>>> s = "this is a string"
>>> a = s.split()
>>> a
['this', 'is', 'a', 'string']
>>> t = (1, 3, 32, 4)
>>> 'is' in s
True
>>> 'is' in a
True
>>> 'is' in a[0]
True
>>> 'is' in t
False
>>> 1 in t
True
>>> 32 in t
True

【讨论】:

    【解决方案2】:

    我认为最简单的方法是在引号中输入单词并立即签入文件,而无需循环:

    'and' in open(r'C:\Users\user\Desktop\something.csv').read().split()
    
    gives: True
    

    或者,如果您知道要检查的单词,您可以将它们传递到一个列表中并使用此代码检查它们以将它们分类为 找到未找到 类别像这样:

    li = ['area','keep','have','sky'] #make a list with the words you want to check
    
    for i in li:
        if i in open(r'C:\Users\user\Desktop\something.csv').read().split():
            print('found:' + i)
        else:
            print('not found:' + i)
    

    这给出了以下内容:

    found:area
    found:keep
    found:have
    not found:sky
    

    或者第三种方式看起来更像你的代码,并且还计算找到它的次数:

    import csv
    with open(r'C:\Users\user\Desktop\something.csv', 'r') as csv_file: 
        csv_reader = csv.reader(csv_file) 
        z=0
        ax=csv_file.read().split()
        if 'and' in ax:
            print('found')
        for line in ax:
            z+=line.count('and')
        print(z)
    

    这给出了:

    found
    191
    

    如果单词在 csv 中。

    【讨论】:

    • 所有的建议对初学者来说真的很有帮助。我结束了使用 GSA 的原始建议并使用它并让它发挥作用。感谢帮助
    • 我是 GSA。什么意思?
    【解决方案3】:

    您可以在 CSV 文件中搜索字符串并打印结果。

    import csv
    # Asks for search criteria from user
    search_parts = input("Enter search criteria:\n").split(",")
    # Opens csv data file
    file = csv.reader(open("C:\\your_path_here\\test.csv"))
    # Go over each row and print it if it contains user input.
    for row in file:
        if all([x in row for x in search_parts]):
            print(row)
    

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2021-09-20
      • 1970-01-01
      相关资源
      最近更新 更多