我需要用“我搜索
”这个词打印每一行text = open("example.txt").read()
start = 0
while 1:
found = text.find("python", start)
if found == -1:
break
for line in found:
print line
start = found + 1
但我收到错误:
TypeError: 'int' object is not iterable (12 line)
答案 0 :(得分:4)
您无法迭代整数found
。相反,迭代文件中的行,并使用if SUBSTRING in STRING
语法;
with open('example.txt') as f:
for line in f:
if 'python' in line:
print(line)
答案 1 :(得分:1)
found
是" python"的(整数)位置,你不能迭代它。
你可能意味着像
found = text.find("python", start)
while found != -1:
# Do something with found:
# ...
start = found + 1
found = text.find("python", start)
但是,由于您明确希望使用包含单词的每一行,因此最好从行开始。使用
for line in open(filename):
或(见phihags回答)
with open(filename) as f:
for line in f:
比尝试一次处理所有文本更好。