gpt4 book ai didi

python - 获取文件Python中某个短语的行号

转载 作者:IT老高 更新时间:2023-10-28 20:34:58 28 4
gpt4 key购买 nike

我需要获取文本文件中短语的行号。这句话可能是:

the dog barked

我需要打开文件,搜索该短语并打印行号。

我在 Windows XP 上使用 Python 2.6


这就是我所拥有的:

o = open("C:/file.txt")
j = o.read()
if "the dog barked" in j:
print "Found It"
else:
print "Couldn't Find It"

这不是家庭作业,它是我正在进行的项目的一部分。我什至不知道如何获取行号。

最佳答案

lookup = 'the dog barked'

with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
print 'found at line:', num

关于python - 获取文件Python中某个短语的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3961265/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com