Python - 对我的CSV字符串查找器的改进

时间:2016-03-17 13:57:06

标签: python csv

我有一个CSV文件,其中有两列 - 一个用于解决问题,另一个用于答案。但是,它仅在您输入CSV文件中显示的字符串时才有效。如何拆分字符串或使程序仅扫描关键字的CSV?

我的代码如下:

def PhoneSupport(): #Second Subprogram created/defined, the main body of the whole program.
    error = 1
    f = open("PhoneSupp CSV.csv", "r") #Opens the CSV file
    rows = re.split("\n", f.read())

    userInput = input("What has happened to your phone?") #Asks the user the desired question
    randInt = random.randint(0,9999) #Random integer used later on

    if userInput == "":
        print("You have not entered any problem.") #Tells the user no problem has been entered and therefore are asked to restart the program
        RestartProgram()

    for index, row in enumerate(rows): #Loop that splits the rows into cells
        cells = row.split(',')
        if userInput in cells: #Searches the CSV file for the matching string (in lower case)
            error = 0
            print("A Solution has been found!:")
            print("")
            print(cells) #Prints the solution, if one has been found
            print("")
            break
        elif userInput == "":
            error = 1
        else:           #If it doesn't, then the error variable is set to 1 for the code below
            error = 1

    if error == 1:
        print("No Solution has been found - Your support ticket is: " + str(randInt)) #Prints error message and the random integer created earlier to act as a support ticket
        print("")
        RestartProgram() #Asks the user to restart
    elif error == 0:
        RestartProgram() #Asks the user to restart

PhoneSupport() #Starting the PhoneSupport subprogram

2 个答案:

答案 0 :(得分:1)

那不是那么简单。您需要优化您想要查找的内容: 您可能想要使用正则表达式

import re
##more of your code here##

for index, row in enumerate(rows): #Loop that splits the rows into cells
    cells = row.split(',')
    if re.search(userinput, cells[0])
        error = 0
        print("A Solution has been found!:")
        print("")
        print(cells[1]) #Prints the solution, if one has been found
        print("")
        break

但是,如果不进一步解析,这样做可能会产生部分结果。

答案 1 :(得分:0)

此代码

for index, row in enumerate(rows): #Loop that splits the rows into cells
    cells = row.split(',')
    if userInput in cells:

将行拆分为包含两个元素的列表 - 问题和答案。

if userInput in cells检查userInput是否与任一元素完全匹配。

您需要if userInput in cells[0]:来搜索问题中的userInput