2016-08-01 90 views
0

文本文件,我有這個文本文件:搜索詞Python中

MemTotal,5,2016-07-30 12:02:33,781 
model name,3,2016-07-30 13:37:59,074 
model,3,2016-07-30 15:39:59,075 

我需要找到與模型線。

我的代碼:

term = "model" 
file = open('file.txt') 
for line in file: 
    line.strip().split('/n') 
    if term in line: 
     print line 
file.close() 

這是輸出:

model name,3,2016-07-30 13:37:59,074 
model,3,2016-07-30 15:39:59,075 

我只需要這一行作爲輸出:

model,3,2016-07-30 15:39:59,075 

我怎樣才能做到這一點?

+0

'項=「模式,」'反正這取決於它是否是一個一般的情況下,或特定的一個 – Samuel

+2

'line.strip ().split('/ n')'什麼都不做。 「strip」和「split」不適用。 –

回答

2

只需更換行:

if term in line: 

符合:

if line.startswith('model,'): 
+0

只是一個小問題。這傢伙說,他需要找到「模型」。如果它介於兩者之間呢?然後,根據OP給出的示例數據,您的代碼將失敗 –

+0

@sameerasy,這是一個正確的答案。 –

+0

是的,如果它不在一開始就會失敗。但基於提供的示例數據,它似乎是一些日誌文件,它總是像這樣開始。 – grubjesic

1

這取決於你的文件中包含。你舉的例子是很輕,但我看到了幾個直接的解決方案,不改變你的代碼太多:

  1. 更換由term = 'model,'term = 'model',這將只顯示你想要的行。

  2. 使用一些附加條件,如「不得包含'name'

像這樣:

term = 'model' 
to_avoid = 'name' 
with open('file.txt') as f: 
    for line in file: 
     line = line.strip().split('/n') 
     if term in line and to_avoid not in line: 
      print line 

其他的看法

  • 你可以使用startswith('somechars')檢查字符串開頭的某些字符
  • 您需要在變量中指定strip()split(\n)的結果,否則不會發生任何事情。
  • 這也是更好地使用關鍵字with,而不是打開/關閉文件
  • 一般情況下,我想你會與這種類型的東西,你正在做的正則表達式得到更好的服務。然而,正如Nander Speerstra的comment指出的那樣,這可能是危險的。
+0

感謝它的工作 –

+1

對'line = line.strip()'行以及'with'的使用有很好的解釋。但是[**當不必要時使用正則表達式**](http://programmers.stackexchange.com/a/113243/239397)。 –

+0

確實。我已經編輯來警告OP。 – BusyAnt

1

您可以通過,分割線和檢查第一場:

term = "model" 
file = open('file.txt') 
for line in file: 
    line = line.strip().split(',') # <--- 
    if term == line[0]:    # <--- You can also stay with "if term in line:" if you doesn't care which field the "model" is. 
     print line 
file.close()