You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何打印CSV文件中包含指定关键词的行?解决现有代码仅支持精确匹配的问题

Got it, let's fix this so your code finds rows that contain the keyword instead of requiring an exact match. Here's what's going wrong and how to adjust it:

Your original code uses ==, which enforces a strict exact match—only when the input keyword is identical to the cell content will it trigger a print. To switch to "contains" logic, we'll use Python's in operator, which checks if a string exists as a substring within another.

Solution 1: Check only the first two columns (matches your original logic)

We'll replace the separate == checks with in and combine them into a single or condition:

import csv
import sys

# Input the keyword to search for
name = input('Enter name to find\n')

# Read the CSV file
csv_file = csv.reader(open('test.csv', "r"), delimiter=",")

# Loop through each row
for row in csv_file:
    # Check if the keyword is present in either the first or second column
    if name in row[0] or name in row[1]:
        print(row)

Solution 2: Check all columns in the row (more flexible)

If you want to search every cell in a row instead of just the first two, use the any() function to iterate through all cells in the row:

import csv
import sys

name = input('Enter name to find\n')

csv_file = csv.reader(open('test.csv', "r"), delimiter=",")

for row in csv_file:
    # Check if the keyword exists in any cell of the current row
    if any(name in cell for cell in row):
        print(row)

To make the search ignore uppercase/lowercase differences (e.g., input "john" matches "John" or "JOHN"), convert both the input and cell content to lowercase before checking:

import csv
import sys

# Convert input to lowercase for case-insensitive matching
name = input('Enter name to find\n').lower()

csv_file = csv.reader(open('test.csv', "r"), delimiter=",")

for row in csv_file:
    # Check each cell (converted to lowercase) for the keyword
    if any(name in cell.lower() for cell in row):
        print(row)

With these changes, your code will now print any CSV row that includes your specified keyword, rather than only exact matches!

内容的提问来源于stack exchange,提问作者DDD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:37:33