2012-11-03 67 views
0

我想使腳本中的參數更容易管理我放在一起,我想我會將一堆相關的項目包裝到字典中,並將字典傳遞出功能。根據需要拉出物體。Python - 使用字典項目作爲對象

其中的一個項目是regEx,我正在努力弄清楚如何正確構建事情,以便我可以使其工作。

在我最初的代碼(沒有字典)。我是「硬」編碼的正則表達式到解析器:

def TopnTail(self,line): 
    topRegEx = re.compile(r'(<!--make_database header end-->)') 
    tailRegEx = re.compile(r'(<!--make_database footer start-->)') 
    searchdumpTopOfPage = topRegEx.search(line) 
    searchdumpBottomOfPage = tailRegEx.search(line) 
    if searchdumpTopOfPage: 
     self.__useLine=1 
    if searchdumpBottomOfPage: 
     self.__useLine=0 
    if self.__useLine == 1: 
     self.trimmedLines = self.trimmedLines + line + "\n" 
    return (self.trimmedLines) 

在「dictionaried」版本我想設置在二傳手的變量:

def siteDetails(): 
    baseDict = {'topRegex':'''re.compile(r'(<!--make_database header end-->)')''', 'tailRegex':'''re.compile(r'(<!--make_database footer start-->)')'''} 
    return baseDict 

,並獲得了編譯正則表達式:

def TopnTail(self,line): 
    topRegEx = baseDict['topRegex'] 
    tailRegEx = baseDict['tailRegex'] 
    searchdumpTopOfPage = topRegEx.search(line) 
    searchdumpBottomOfPage = tailRegEx.search(line) 
    if searchdumpTopOfPage: 
     self.__useLine=1 
    if searchdumpBottomOfPage: 
     self.__useLine=0 
    if self.__useLine == 1: 
     self.trimmedLines = self.trimmedLines + line + "\n" 
    return (self.trimmedLines) 

但是這將引發一個錯誤:

line 35, in TopnTail 
searchdumpTopOfPage = topRegEx.search(line) 
AttributeError: 'str' object has no attribute 'search' 

我正在猜測這意味着它實際上並沒有創建正則表達式對象,但仍在傳遞字符串。

我明白,我可能在這裏違反了3項基本規則......但是關於如何使它工作的任何建議都是太棒了......(也是,第一次玩類和詞典......所以請如果我真的搞砸了,那就去吧!)

回答

1

這個怎麼樣?

baseDict = { 
    'topRegex': r'(<!--make_database header end-->)' 
} 

而在你TopnTail方法

topRegEx = re.compile(baseDict['topRegex']) 

與你有什麼問題,是你分配一個到topRegEx包含'''re.compile(r'(<!--make_database header end-->)')'''。由於str沒有方法search,所以出現錯誤。

它仍然是編譯你的正則表達式,並使用返回的對象。如果您需要更改正則表達式模式,或者想要動態定義它,則將正則表達式的內容分割爲字典將有所幫助。

+0

Yupe。那是票。謝謝。它也大大簡化了論點。我從來沒有意識到'r'是一個標籤(像'b')直到現在。謝謝你!在你的編輯 - 這就是爲什麼我想打破它 - 所以它很好,我知道我在正確的球場! –

+1

'r'只是表示一個原始字符串。我甚至不認爲這是必要的,它被用來阻止角色逃跑。 – Aesthete

+0

啊,好的。謝謝。這保存了我又一次快速谷歌搜索! –