Skip to main content
 首页 » 编程设计

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

2025年05月04日11findumars

我想知道当我阅读时如何知道 .txt 中的位置。

这是我的文字

cat dog monkey bird

这是我的打印

Word: cat Position: line 1 , word 1 (1,1)

有什么想法吗?

请您参考如下方法:

foo.txt:

asd 
asd 
asd 
ad 
I put returns between ....... 
asd 
sad 
asd 

代码:

>>> 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)