如何在程序中输入大小写混合的单词,以便它读取CSV
文件并打印正确的解决方案?
在这种情况下,我希望这样,当用户输入mY sOuNd Is BrOkEn
时,读者会选择sound
关键字并打印链接的回复。
problem=input("\nWhat problem do you have with your phone?\n\n ")
#Prints 'What problem do you have with your phone?' and expects an answer in the CSV file.
space=problem.split(" ")
#Splits their response into a list for each word used.
openfile=csv.reader.lower()(open("task2.csv"))
#Opens task2 file and creates a CSV Reader for it.
read=[row for row in openfile]
#Outputs the information from the CSV into a 2D list.
for x in range(0,len(space)):
#Loops through the user input
for y in range(0,len(read)-1,2):
#Loops through each row in the CSV.
if (space[x] in read[y]):
#Checks if the current word is in the current row of the list.
print(read[y+1][0])
#Prints a link to your response.
print("\nThank you for using GetRekt Troubleshooting.\n")
#Prints 'Thank you for using GetRekt Troubleshooting.'
elif problem==("Exit"):
print('You have decided to terminate the program. Goodbye.')
sys.exit(0)
else:
continue
restart()
在这里,.lower()函数不起作用。请帮忙!
答案 0 :(得分:0)
在您当前的示例中,read[y]
对应一行。这意味着read[y]
不是字符串,而是表示行的list
对象。
您需要将read
定义为:
read=[[field.lower() for field in row] for row in openfile]
这样您就可以在每行中的每个元素上运行lower()
。
现在只需检查关键字是否在一行中:
if (space[x].lower() in read[y]){
...
}
答案 1 :(得分:0)
lower()
将起作用。不应在csv.reader.lower()(open("task2.csv"))
上执行它,而应该对字符串变量执行。
示例:
# open using csv reader
openfile = csv.reader("task2.csv", delimiter=',', quotechar='"')
...
# compare strings using lower()
if (space[x].lower() in read[y].lower()):
...