如何知道一个位置(.txt)

a3r*_*der 1 python

我想知道如何知道,当我读到时.txt中的位置.

这是我的txt

猫狗猴子鸟

这是我的印刷品

单词:cat位置:第1行,单词1(1,1)

任何的想法?

utd*_*mir 5

foo.txt的:

asd
asd
asd
ad
I put returns between .......
asd
sad
asd
Run Code Online (Sandbox Code Playgroud)

码:

>>> def position(file,word):
...     for i,line in enumerate(file): #for every line; i=linenumber and line=text
...         s=line.find(word) #find word
...         if s!=-1: #if word found
...             return i,s # return line number and position on line
...
>>> position(open("foo.txt"),"put")
(4, 2) # (line,position)
Run Code Online (Sandbox Code Playgroud)