读取csv并检查fi中的术语

2024-04-19 18:07:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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文件,然后它应该告诉我,如果是或不是


Tags: orcsvthe代码inimportyouif
2条回答

代码中有一些基本问题。你知道吗

  1. 你从不使用导入csv
  2. 您从未定义count变量
  3. 您从未定义column列表
  4. 你从未从文件中读取任何数据
  5. 你从不关闭文件

我讨厌完全重写别人的代码,但你的代码需要一些帮助。此代码将完成您希望它完成的任务:

word = input("Please enter a word: ")
delimiter = ","

with open("TEST.csv", 'r') as file:
    content = file.read().replace('\n', '').split(delimiter)

if word in content:
    print("The word you entered is in row {}".format(content.index(word)))
else:
    print("The word you enterd is NOT in the file")

让我带你看看这段代码的作用和方法。你知道吗

  1. 我们得到的信息和你一样,有^{}
  2. 我们使用^{}打开文件,完成后自动关闭
  3. 我们read将文件作为一个大字符串,replace所有的换行符(“\n”)都用空字符串和split逗号上的字符串。我们将字符串拆分为一个逗号列表,因为这是一个csv文件,意味着所有内容都用逗号分隔。如果使用不同的分隔符,只需更改分隔符变量。你知道吗
  4. 测试单词是否出现在列表中的任何位置。你知道吗
  5. (a)如果它确实出现,打印它确实出现了,以及它的索引(它的行)

    (b)如果没有出现,打印它没有

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

此代码将不起作用,因为您有一个未定义的“count”。你还需要程序能够读取文件,你错过了一点点代码。另外,因为你有你正在阅读的专栏,你应该有一个

for column in read:
count = count + 1

别忘了将“count”本身设置为一个变量。 祝你好运

相关问题 更多 >