2014-06-25 28 views
0

當前該程序找到所有包含您要求它查找的特定單詞的行,但是如何更改它以便將所有多行號存儲爲不同的值,即I然後可以操作。或者如何找到該短語的具體發生。根據用戶輸入查找文件中的一行

a = raw_input("Please enter something: ") 
lookup = a 
with open('FileName') as myFile: 
    for num, line in enumerate(myFile, 1): 
     if lookup in line: 
      print 'found at line:', num 
+0

我怎樣才能得到一個特定的事件行號?因爲目前它會打印出特定短語的所有行號,但我只想獲得第三次出現。 – Nick

回答

1

而不是打印num,你可以將它存儲到一個列表(或兩者兼有)。

found = [] 
for num, line in enumerate(myFile, 1): 
    if lookup in line: 
     print 'found at line:', num 
     found.append(num) 
     # found.append((line,num)) # use this if you want to store both the line and the number 

的這個簡短的版本是:

found = [num for num, line in enumerate(myFile, 1) if lookup in line] 

短版與num印刷:

found = [num for num, line in enumerate(myFile, 1) if lookup in line and not print(num)] 

這會給你一個列表found存儲所有nums針對你的查找成功了。

+0

或更低的可讀性:'如果在行中查找,'enumerate(myFile,1)'中找到= [(num,line)]' –

+0

我會如何將每個行號保存爲一個單獨的變量? – Nick

+0

@Nick您可以通過索引到「找到」來訪問這些值,例如, 'found [0]'是查找成功的第一行的'num','找到[1]'是第二行的'num',依此類推。你在問什麼? – timgeb

0
lookup = raw_input("Please enter something: ") 
with open("FileName") as myfile: 
    found = {num: line for (num, line) in enumerate(myfile, 1)} 

這就是我該怎麼做的。該字典比較是有點簡潔,而且闡述了它的作用:

found = {} # empty dict 
for num, line in enumerate(myfile, 1): 
    found[num] = line 

這將讓你與字典玩像這樣:

for lineno, line in found.items(): 
    print "{:03}: {}".format(lineno, line) 

編輯爲您的問題評論意見

我個人會使用正則表達式,而不是試圖將它拼湊在一起。然而,爲了回答你的問題:

startsentry="DATA STARTS ON THE NEXT LINE" 
endsentry="DATA ENDS ON THE PREVIOUS LINE" 

with open('path/to/file') as myfile: 
    for line_num, line in enumerate(myfile, 1): 
     if startsentry in line: 
      _start = line_num+1 
     if endsentry in line: 
      _end = line_num 
    data_is_in = (_start, _end) 
+0

有沒有辦法找到使用關鍵字行,然後打印所有的東西,直到我擊中另一個關鍵字的東西? – Nick

+0

@Nick編輯.... –

+0

我發現了一個非常簡單的方法來做到這一點:對於我列舉的行(打開(「FILE」)): 如果i> = 95且i <97: \t print line,如果i> = 133且i <134: 打印行, 對於i,行中列舉(打開(「FILE」)): 如果i > = 196和i <2197: print line, for i,line in enumerate(open(「FILE」)): if i> = 2225 and i <4227: print line, 現在我只需要做是能夠得到行號我變得超級卡住:( – Nick

0

我建議了不同的方法,像:

lines = [] 
with open("file") as f: 
    lines = f.readlines() 

phrases = filter(lambda x: "foo" in x[1], enumerate(lines)) 
print phrases 

現在你留下了行號和短語對匹配「foo」的數組。

更新:更改爲枚舉每個評論(謝謝!)。

+0

記住你的'枚舉'內建! 'line = enumerate(f)'與你的'lines = f.readlines();是一樣的。 lines = zip(...)'除了少得多的內存密集:) –

相關問題