Skip to main content
 首页 » 编程设计

python之读取 csv 并检查文件中的术语

2024年10月01日7wayfarer

import csv 
 
word = input("please enter a word: ") 
file = open('TEST.csv', 'r') 
 
if column[0] in word or column[1] in word or column[2] in word or column[3] in word or column[4] in word: 
    print("The word you entered if in row " +str(count)) 
else: 
    print("The word you entered is NOT in row " +str(count)) 

我的代码不工作,我希望代码允许我输入一个单词并查找它是否在 csv 文件中,然后它应该告诉我它是否在。

请您参考如下方法:

import csv 
 
word = input("please enter a word: ") 
file = open('TEST.csv', 'r') 
read = csv.reader(file) 
count = 0 
 
for column in read: 
    count = count + 1 
 
if column[0] in word or column[1] in word or column[2] in word or column[3] in word or column[4] in word: 
    print("The word you entered if in row " +str(count)) 
else: 
    print("The word you entered is NOT in row " +str(count)) 

此代码无效,因为您有一个未定义的“计数”。此外,您还需要程序能够读取文件,而您错过了那一点代码。也因为你有你正在阅读的专栏,你应该有一个

for column in read: 
count = count + 1 

不要忘记将“计数”本身设置为变量。 祝你好运