简体   繁体   中英

Using Python to parse CSV to find specific string

Completely new to python (and programming). Trying to write a python script that reads a CSV file and searches for a specific string. The string represents an instance which will eventually aid in a larger script (performing additional task). With the script below I can read the CSV but I don't know how I can get the script to look for a specific string:

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

I have tried using splits, append, pandas and other options but I am not able to get it to work. Would appreciate any assistance.

The in operator can help you determine if something is in another thing, as shown below:

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

Some examples from 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

I think the easiest way would be to just type the word in quotes and check in the file immediately without a loop:

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

gives: True

Or if you know what words you want to check, you can pass them in a list and check them with this code to categorise them in found and not found categories like this:

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)

Which gives the following:

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

Or a third way that looks more like your code and also counts how many times it is found:

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)

Which gives:

found
191

If the word is in the csv.

You can search for a string in a CSV file and print the results.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM