2011-08-05 39 views
0

我一直在努力使用Python來執行條件附加/擴展特定文本的文本文件。我很抱歉,如果這太基本了,並且已經在這裏討論過或者其他:(Python中的條件添加

關於代碼(附件),我只需要在包含「description」的語句下添加語句「mtu 1546」它不存在。另外,我希望能夠在界面語句(和/或上面的mtu語句,如果有的話)下添加「description TEST」語句,只要不存在,我就使用python 2.7。

這裏是我的代碼:

import re 

f = open('/TESTFOLDER/TEST.txt','r') 
interfaces=re.findall(r'(^interface Vlan[\d+].*\n.+?\n!)',f.read(),re.DOTALL|re.MULTILINE) 

for i in interfaces: 
    interfaceslist = i.split("!") 
    for i in interfaceslist: 
     if "mtu" not in i: 
      print i 


f.close() 

print語句工作正常的情況,因爲它是能夠正確打印有趣的線,但是我的要求是添加(追加/擴展)所需的語句到列表中,以便我可以進一步使用它來解析和東西。在嘗試附加/擴展功能時,解釋器會將其視爲字符串對象。以下是示例源文件(文本)。我將解析的文本文件的大小很大,所以只添加有趣的文本。

! 
interface Vlan2268 
description SNMA_Lovetch_mgmt 
mtu 1546 
no ip address 
xconnect 22.93.94.56 2268 encapsulation mpls 
! 
interface Vlan2269 
description SNMA_Targoviste_mgmt 
mtu 1546 
no ip address 
xconnect 22.93.94.90 2269 encapsulation mpls 
! 
interface Vlan2272 
mtu 1546 
no ip address 
xconnect 22.93.94.72 2272 encapsulation mpls 
! 
interface Vlan2282 
description SNMA_Ruse_mgmt 
no ip address 
xconnect 22.93.94.38 2282 encapsulation mpls 
! 
interface Vlan2284 
mtu 1546 
no ip address 
xconnect vfi SNMA_Razgrad_mgmt 
! 
interface Vlan2286 
description mgmt_SNMA_Rs 
no ip address 
xconnect 22.93.94.86 2286 encapsulation mpls 
! 
interface Vlan2292 
description SNMA_Vraca_mgmt 
mtu 1546 
no ip address 
xconnect 22.93.94.60 2292 encapsulation mpls 
! 
+0

你有沒有注意到,你使用變量i在這兩個for循環? :) –

+0

實際上,Python知道它是一個不同的變量,但是對於人類的讀者來說,它是令人困惑的。 –

+0

謝謝邁克爾。這也正是我的想法.. – user531942

回答

1

你的問題的基本答案很簡單。字符串是不可變的,所以你不能將它們或extend。你必須使用連接來創建一個新的字符串。

>>> print i 
interface Vlan2286 
description mgmt_SNMA_Rs 
no ip address 
xconnect 22.93.94.86 2286 encapsulation mpls 

>>> print i + ' mtu 1546\n' 
interface Vlan2286 
description mgmt_SNMA_Rs 
no ip address 
xconnect 22.93.94.86 2286 encapsulation mpls 
mtu 1546 

然後,您必須將結果保存到變量名稱或某種容器中。你可以只將其保存到我喜歡這樣:

i = i + ' mtu 1546\n' 

或像這樣:

i += ' mtu 1546\n' 

但在這種情況下,列表理解可能是有用的...

def add_mtu(i): 
    return i if "mtu" in i else i + " mtu 1546\n" 

for iface in interfaces: 
    interfaceslist = iface.split("!") 
    updated_ifaces = [add_mtu(i) for i in interfaceslist] 

注爲了清楚起見,我用iface替換了第一個i。此外,在我看來,interfaces目前只有一個iface。也許你需要這個for循環,但如果沒有,它會簡化的東西去除它。

+0

非常感謝,它看起來很棒!我會盡快嘗試,讓你知道..再次感謝.. – user531942

+0

senderle - 它與MTU很好。關於描述聲明與MTU一起如何。我如何着手整合代碼的這一面?我必須爲此創建不同的功能嗎?任何代碼將不勝感激..我有一些情況下,可能會從文本文件中丟失「mtu」或「description」語句中的任何一個或兩者。再次感謝所有幫助 – user531942

+0

您可以修改當前的'add_mtu'函數。不要在''中返回'我如果「mtu」的結果',將它保存爲一個變量名稱,並用描述做同樣的事情。 – senderle

1

如果你可以看到整個文件:

import re 

f = open('/TESTFOLDER/TEST.txt','r') 
text = f.read() 

text = re.sub(r"(?m)(^interface Vlan\d+.*\n(?! description)", r"\1 description TEST\n", text) 
text = re.sub(r"(?m)(^interface Vlan\d+.*\n description .+\n)(?! mtu)", r"\1 mtu 1546\n", text) 
+0

工程就像一個魅力:)非常感謝,..非常感謝,真的! – user531942