【发布时间】:2020-11-23 00:50:30
【问题描述】:
遍历文件并搜索文件中出现的几个单词。我写了列表理解,试图将匹配的单词存储在每个阅读行的列表中。
search_strings = ["happy", "sad", "between"]
fio = open("text.txt", encoding="utf-8")
# reading file and trying to find occurences of search_string in text file
for line in fio:
# first attempt: not what I wanted
found_list_1 = [word in line for word in search_string]
# second attempt: what I wanted
found_list_2 = [word for word in search_string if word in line]
fio.close()
打印出两个构造列表的结果:
found_list_1 打印出来时给我布尔值
[True, False, False]
found_list_2 返回从文件中读取的每一行中找到的字符串。
["happy"]
我试图了解 found_list_1 的列表理解的行为,为什么它返回布尔值而不是匹配的单词?
【问题讨论】:
-
found_list_1的条目来自您的表达式word in line,它返回一个布尔值。
标签: python file search list-comprehension