2015-08-25 39 views
1

我有一個很大的txt文件,我想在其中查找一組特定的字符串並提取它們後面的數字。例如:在python中找到字符串的位置

26.08.15 14:52:04 Pressure 1.02 Temperature 32.5 NOb 10993 VB 28772 
.... <other stuff> 
26.08.15 14:53:06 Pressure 1.03 Temperature 31.6 NOb 10993 VB 28008 
.... <other stuff> 

我希望能夠找到字符串=溫度,並提取後面的數值。我看過一些例子,告訴我字符串是否存在,但沒有告訴我它在哪裏,或者如何索引它後面的信息。這是可以用Python完成的嗎?

+0

是的,可以做到。你可以包含一些代碼來顯示你的嘗試嗎? – Cyphase

+0

需要樣本輸入和輸出。並且還需要您的嘗試代碼 –

回答

2

可以,或者通過使用Python的正則表達式使用相匹配的

import re 
with open("example.txt") as f: 
    for line in f: 
     m = re.match(".* Temperature (.*?) .*", line) 
     if m: 
      try: 
       number = float(m.group(1)) 
       print(number) 
      except ValueError: 
       pass # could print an error here because a number wasn't found in the expected place 
0

這可以通過手動讀取文件字的字來實現正則表達式組。在我看來,使用正則表達式會導致更簡潔的代碼而不會丟失可讀性,所以我將重點關注該解決方案。

從爲re模塊(https://docs.python.org/3/library/re.html)Python文檔:

(?<=...)相配如果字符串中的當前位置是由匹配...之前,在當前位置結束。

這個例子查找一個字下面一個連字符:

m = re.search('(?<=-)\w+', 'spam-egg') 
m.group(0) 

在你的榜樣,你要「溫度」的每次出現的任何數量的數字\d+,可選文字小數點後搜索\.?和更多數字\d+?re.findall()函數可能會有用。

2

我討厭正則表達式,所以這裏是純粹的Python解決方案。

lines = "26.08.15 14:52:04 Pressure 1.02 Temperature 32.5 NOb 10993 VB 28772 .... 26.08.15 14:53:06 Pressure 1.03 Temperature 31.6 NOb 10993 VB 28008 ...." 
lines = lines.split() 
for n, word in enumerate(lines): 
    if word in ['Temperature', 'Pressure']: 
     print(word, lines[n+1]) 
相關問題