我有一个清单:
names = ['Jim','Billy','Diana']
我有一个文件,每行是:
Jim and Billy went to see Diana.
Diana was at the Mall.
Billy and Diana are siblings.
我需要输出文件看起来像:
'Jim', 'Billy', 'Diana'
'Diana'
'Billy', 'Diana'
以下是我所得到的不起作用:
f = open("storyfile.txt","r")
names = ['Jim','Billy','Diana']
for line in f:
if names in line:
print(names)
f.close()
返回:
TypeError: 'in <string>' requires string as left operand, not list
不确定我的做法可能与众不同。
答案 0 :(得分:1)
当你执行if names in line
时,你指示你的程序看看整个数组是否在单个字符串中......它无法进行比较,所以它会抱怨。
您需要将文件中的每一行拆分为您可以搜索的单独字词:
for line in f:
for word in line.split(" "):
if word in names:
print(word + ","),
print("\n")
输出:
Jim, Billy,
Diana,
Billy, Diana,
在每个印刷线的末尾都会留下额外的逗号,但我相信你可以找出一些逻辑来摆脱它......
答案 1 :(得分:0)
f = open("storyfile.txt","r")
names = ['Jim','Billy','Diana']
for line in f:
print([name for name in names if name in line])
f.close()