使用Python解析CSV以查找特定的字符串

时间:2018-08-08 12:09:24

标签: python python-3.x csv scripting

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

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

我尝试使用split,append,pandas和其他选项,但是我无法使其正常工作。不胜感激。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我认为最简单的方法是只在引号中输入单词并立即检查文件而不会出现循环:

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

gives: True

或者,如果您知道要检查的单词,则可以将它们传递到列表中,并使用此代码对其进行检查,以将其分类为 found not found 类别像这样:

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中。

答案 2 :(得分:0)

您可以在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)