简体   繁体   English

为什么我的if elif循环无法一致地在数据中找到字符串

[英]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. 我的代码是从csv文件读取url,对其内容进行GET,解析响应并将输出写入第二个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. 换句话说,并非在所有情况下都会填充csv文件的所有列。

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. 我的4行测试文件的构建方式是,在第一次迭代中缺少关键字,在第二次迭代中缺少关键字,在第三次迭代中缺少关键字,最后一次出现。下面的代码将找到关键字,并在第一次迭代时正确填充csv,但它在最后一个实例中找不到。 I can't figure out what is wrong with my if/elif loop: 我无法弄清楚if / elif循环出了什么问题:

        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]". 如果工作正常,则最后一个“其他”将是另一个“ [PCI]”。 It populates the csv file accordingly the first time, but after that it populates as if the keyword never appears again. 它将第一次相应地填充csv文件,但此后它将填充,就好像该关键字不再出现一样。

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. 碰巧[PCI]是第二个实例中的第一个单词。 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. 因此,在另一种情况下,由于它不是第一个单词,因此它不会触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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