簡體   English   中英

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

[英]Using Python to parse CSV to find specific string

對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)

我曾嘗試使用拆分、附加、熊貓和其他選項,但我無法讓它工作。 將不勝感激任何幫助。

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

我認為最簡單的方法是在引號中輸入單詞並立即簽入文件而無需循環:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM