当我读到时,我想知道如何知道.txt中的位置。
这是我的txt
猫猫猴子
这是我的印刷
单词:cat位置:第1行,单词1(1,1)
任何想法?
答案 0 :(得分:5)
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)
答案 1 :(得分:4)
这适用于此给定文件:
blah bloo cake
donky cat sparrow
nago cheese
代码:
lcount = 1
with open("file", "r") as f:
for line in f:
if word in line:
testline = line.split()
ind = testline.index("sparrow")
print "Word sparrow found at line %d, word %d" % (lcount, ind+1)
break
else:
lcount += 1
会打印:
Word sparrow found at line 2, word 3
你应该能够很容易地修改它,以实现我希望的功能或不同的输出。
虽然我仍然不确定这是不是你想要的......
次要编辑: 作为一个功能:
def findword(objf, word):
lcount = 1
found = False
with open(objf, "r") as f:
for line in f:
if word in line: # If word is in line
testline = line.split()
ind = testline.index(word) # This is the index, starting from 0
found = True
break
else:
lcount += 1
if found:
print "Word %s found at line %d, word %d" % (word, lcount, ind+1)
else:
print "Not found"
使用:
>>> findword('file', "sparrow")
Word sparrow found at line 2, word 3
>>> findword('file', "donkey")
Not found
>>>
耸肩这不是我给它的最佳方法,但它再次起作用。
答案 2 :(得分:1)
基本理念
line_no += 1
; in
),然后使用list.index(word)
获取索引,将该索引存储在某个变量中word_no = list.index(word)
line_no
和word_no
有很多更好的解决方案(以及更多pythonic
个),但这会给你一个想法。