2011-04-15 42 views
1

我想知道如何知道,當我閱讀時.txt內的位置。如何知道一個位置(.txt)

這是我的txt

貓狗猴鳥

這個我打印

字:貓位置:1號線,字1(1,1)

有什麼想法?

+0

......的位置_(將繼續以Ignacio的評論)_ – eyquem 2011-04-15 19:34:46

+0

寫一個單詞的位置 – A3R 2011-04-15 19:37:22

+0

他想搜索一個單詞,然後打印line_no和word_no。 – helpermethod 2011-04-15 19:39:29

回答

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

聳聳肩不是我給它的最好的方法,但它再次運作。

+0

而不是捕捉異常,使用'in'來檢查元素是否是列表的一部分,或使用'find'並檢查返回值。 – helpermethod 2011-04-15 19:47:55

+0

增加了'if .. in'部分而不是'try .. except',謝謝。在這裏不使用find(),因爲它會返回字符位置,而不是實際的字(至少,這是它爲我做的)。 – TyrantWave 2011-04-15 20:02:04

+0

太棒了!它對我來說更好,因爲,首先,我在字典中得到了全部詞彙。謝謝大家 – A3R 2011-04-16 01:15:28

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

Blerg,我忘了你可以在那裏爲我排隊。爲你+1! – TyrantWave 2011-04-15 19:48:25

+0

-1 Downvoted,因爲它提供了一個完整的解決方案,沒有任何評論該功能實際上在做什麼。 – helpermethod 2011-04-15 19:48:59

+0

@Helper Method,我認爲Python足夠清晰,但現在添加了評論,謝謝:)。 – utdemir 2011-04-15 19:54:32

1

基本思路

  1. 打開文件
  2. 遍歷線
  3. 對於每行讀取,增加一些計數器,例如line_no += 1;
  4. 分割線的空白(你會得到一個列表)
  5. 檢查列表中包含單詞(使用in),然後使用list.index(word)獲得索引,該索引存儲在某個變量word_no = list.index(word)
  6. 打印line_noword_no如果這個詞被發現

有很多更好的解決方案在那裏(多pythonic的),但是這給你的想法。

相關問題