简体   繁体   中英

How to iterate through a list of strings generated from a list of lists

I'm trying to write a function that will state True if a sms message has links and False if a sms message doesn't have links. I am using a csv file which first was imported as a list of lists. I converted it to a list of strings because I wanted to convert each string into a list so that I could iterate over the words in each string until I got to a word beginning with 'http'. The output I get is just a single value False, so I think that this code is not iterating through each message in the list of strings.

import csv


def read_csv():
    messages = []
    with open('spam.csv', newline='', encoding='latin-1') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
        for row in spamreader:
            string_row = str(row[1])
            messages.append(string_row)
   for string in messages)
    csvfile.close()
    return messages


def has_links(messages):
    txt_messages = messages
    values = []
    for message in txt_messages:
        sing_words = list(message)
        message_value = False
        for word in sing_words
            if word == 'http':
                message_value = True
                values.append(message_value)
            else:
                message_value = False
                values.append(message_value)
        return message_value


def main():
    messages = read_csv()
    print(has_links(messages))
main()



It returns a single value (False), not the list of values computed by has_links().
  1. You're using return message_value at your 1st iteration itself and therefore, it returns only 1 value and comes out of the method.
  2. I'm not sure if you intended to use yield.
  3. Also, I think the logic is flawed.
  4. sing_words = list(message) would just separate each characters and you would be looping over individual characters. So you'll always get False.

Code:

def has_links(messages):
    txt_messages = messages
    values = []
    for message in txt_messages:
        message_value = False
        if 'http://' in message:
            message_value = True
            values.append(message_value)
        else:
            message_value = False
            values.append(message_value)
    return values

OR

def has_links_v2(messages):
    txt_messages = messages
    for message in txt_messages:
        if 'http://' in message:
            yield True
        else:
            yield False

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