gpt4 book ai didi

python - 在外部文本文件中查找字符串所在的行号

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:21 28 4
gpt4 key购买 nike

我正在尝试创建一个程序,它从用户输入的字符串中获取输入并在文本文件中搜索该字符串并打印出行号。如果该字符串不在文本文件中,它将打印出来。我该怎么做?此外,我不确定我目前使用的 for 循环是否适用于此,所以任何建议/帮助都会很棒 :)。

我目前拥有的:

file = open('test.txt', 'r')
string = input("Enter string to search")
for string in file:
print("") #print the line number

最佳答案

你可以实现这个算法:

  • 初始化一个计数器
  • 逐行阅读
  • 如果行与目标匹配,则返回当前计数
  • 增加计数
  • 如果到达末尾没有返回,则该行不在文件中

例如:

def find_line(path, target):
with open(path) as fh:
count = 1
for line in fh:
if line.strip() == target:
return count
count += 1

return 0

关于python - 在外部文本文件中查找字符串所在的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47189680/

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