我正在尝试编写一个函数,如果一条短信包含链接,则状态为True;如果一条短信没有链接,则状态为False。我正在使用一个首先导入为列表列表的csv文件。我将其转换为字符串列表,因为我想将每个字符串转换为列表,以便可以迭代每个字符串中的单词,直到获得以'http'开头的单词。我得到的输出只是单个值False,所以我认为这段代码不会遍历字符串列表中的每个消息。
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().
答案 0 :(得分:0)
代码:
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