简体   繁体   中英

why does my if elif loop fail to consistently find string in data

My code is reading urls from a csv file, doing a GET on their content, parsing the response, and writing output to a second csv. If a keyword is found, I need it to output certain data; if not found, it should output a subset of that data. In other words, not all columns of the csv file would be populated in all cases.

My 4 row test file is constructed so that the keyword is missing in the first iteration, present in the second, missing in third, present in last.The code below will find the keyword and populate the csv correctly the first time it iterates through, but it doesn't find it in the last instance. I can't figure out what is wrong with my if/elif loop:

        counter = 0
        for row in list_reader:

            key_id = row['keyId']
            ex_id = row['key']
            get_response = key.get_item(row['keyId'])
            #get_item is a method from the imported Client
            length = (get_response['length'])
            word = (get_response['transcript']['words'][0]['w'])
            if word != "[keyword1]" and word != "[keyword2]":
                print "other",counter
                results_writer.writerow([key_id,ex_id,length])

            elif word == "[keyword1]":
                print word, counter
                x = (get_response['value1'])
                y = (get_response['value2'])
                counter = counter + 1                
                results_writer.writerow([key_id,ex_id,length,x,y])

With this the output from the terminal is:

    other 0
    [PCI] 0
    other 1
    other 1                

If it were working properly, the last "other" would be another "[PCI]". It populates the csv file accordingly the first time, but after that it populates as if the keyword never appears again.

How can I fix the loop so it iterates successfully to find the keyword after the first time?

(Posted on behalf of the question author) .

I found the problem. It happened that [PCI] was the first word in the 2nd instance. My word variable only would find the first word. So in the other instance, since it wasn't the first word, it didn't trigger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM