2017-10-05 119 views
0

我想寫一個小程序/類,我在文件中找到一定的文本塊。然後我從該塊中提取某些信息並簡化並打印/返回。Python程序迭代和打印使用

此:

it /'properties'/'someJenkinsInformation'/'strategy(class:hudson.LogRotator)' 
{ 
'daysToKeep'('90') 
'numToKeep'('300') 
'artifactDaysToKeep'('3') 
'artifactNumToKeep'('3') 
} 

要這樣:

logRotator(90, 300, 3, 3) 

我有什麼至今:

# Search test.txt for 'LogRotator' 
def find_text(self): 
    super.find_text() 
    self.convert_to_string() 
    # now that we have found our line, find the next piece 


# From find_text print 'logRotator(90, 300, 3, 3)' 
def create_text(): 
    j = 0 

    while self.file_text[line_num + j].strip() != "}": 
     while self.file_text[line_num + j].strip() != ")": 
      match = re.search(r"[0-9]+", self.file_text[line_num + j]) 
    # this is mostly where I get lost in 
    # how to iterate through the above block and how to pull out what I 
    # need in order to print 
+0

什麼是超類?不應該'find_text()'採取一個參數告訴它要搜索什麼? – Barmar

+0

'line_num'是什麼? – Barmar

+0

將每行中的數字追加到列表中。當循環結束時,可以使用'.join'將列表變成字符串'「90,300,3,3」' – Barmar

回答

1

我不是你的要求完全清楚。這可能是你需要的技術。

它涉及逐行解析,當遇到'{'時開啓處理,並在看到匹配的'}'時退出。

import re 

processing = False 
result = 'logRotator(' 
with open('temp.txt') as text: 
    for line in text: 
     if line.startswith('{'): 
      processing = True 
     elif line.startswith('}'): 
      break 
     else: 
      if processing: 
       m = re.search('\d+', line) 
       if m: 
        result += '%s, '%m.group() 
print (result[:-2]+')') 

這是輸出。

logRotator(90, 300, 3, 3) 
+0

謝謝!我幾乎在那裏,這是一個巨大的幫助。 –

+0

非常歡迎。祝好運與其餘。 –