回答
這會工作爲這個給定的文件:
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
>>>
聳聳肩不是我給它的最好的方法,但它再次運作。
而不是捕捉異常,使用'in'來檢查元素是否是列表的一部分,或使用'find'並檢查返回值。 – helpermethod 2011-04-15 19:47:55
增加了'if .. in'部分而不是'try .. except',謝謝。在這裏不使用find(),因爲它會返回字符位置,而不是實際的字(至少,這是它爲我做的)。 – TyrantWave 2011-04-15 20:02:04
太棒了!它對我來說更好,因爲,首先,我在字典中得到了全部詞彙。謝謝大家 – A3R 2011-04-16 01:15:28
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)
Blerg,我忘了你可以在那裏爲我排隊。爲你+1! – TyrantWave 2011-04-15 19:48:25
-1 Downvoted,因爲它提供了一個完整的解決方案,沒有任何評論該功能實際上在做什麼。 – helpermethod 2011-04-15 19:48:59
@Helper Method,我認爲Python足夠清晰,但現在添加了評論,謝謝:)。 – utdemir 2011-04-15 19:54:32
基本思路
- 打開文件
- 遍歷線
- 對於每行讀取,增加一些計數器,例如
line_no += 1
; - 分割線的空白(你會得到一個列表)
- 檢查列表中包含單詞(使用
in
),然後使用list.index(word)
獲得索引,該索引存儲在某個變量word_no = list.index(word)
- 打印
line_no
和word_no
如果這個詞被發現
有很多更好的解決方案在那裏(多pythonic
的),但是這給你的想法。
- 1. 如何知道一個點的位置?
- 2. 如何知道一個位置(如:(CLLocation *)newLocation))是否在路上?
- 3. 如何知道數組的下一個空閒位置
- 4. 如何知道ItemTemplate的序號位置
- 5. 如何排序表知道行位置?
- 6. 如何知道mysql my.cnf的位置
- 7. 如何知道NullReferenceException的確切位置
- 8. 如何知道SemanticZoom的滾動位置?
- 9. 我如何知道「Program Files」的位置?
- 10. 如何知道javascript的輸入位置
- 11. 如何知道位置是地圖中另一個位置的前/後的位置
- 12. 的Python API知道位置
- 13. R:知道表(一個或多個),如何calc下位數(S)
- 14. 如何知道庫函數在哪個位置?
- 15. Django如何知道用戶來自哪個位置?
- 16. 展示位置如何知道要創建哪個佈局?
- 17. 如何知道角色將在哪個位置輸入?
- 18. 如何知道用戶點擊UITableViewCell中的哪個位置?
- 19. 我如何知道這個實例被釋放的位置?
- 20. 如何在android中知道通知的位置
- 21. 如何知道某個位置是在路上還是在人行道上?
- 22. C#打開一個不知道位置路徑的進程
- 23. 如何知道rebot.py放置日誌和報告的位置?
- 24. 有誰知道如何根據txt文件返回一個網格到shell中?
- 25. 如何知道閃爍的管道字符在一個字符串中的哪個位置?
- 26. 如何知道用戶何時取消HTML5地理位置?
- 27. 如何知道一個BPM流程succeded
- 28. 如何知道一個Linux模塊
- 29. 如何知道一個void運行?
- 30. 想知道如何換一個UILabel
......的位置_(將繼續以Ignacio的評論)_ – eyquem 2011-04-15 19:34:46
寫一個單詞的位置 – A3R 2011-04-15 19:37:22
他想搜索一個單詞,然後打印line_no和word_no。 – helpermethod 2011-04-15 19:39:29