2011-11-15 65 views
1

我試圖將一個Python程序移植到Ruby,但我對Python完全無知。如何將Python程序移植到Ruby

你能給我什麼建議嗎?我想運行sampletrain方法。但是,我不明白爲什麼features=self.getfeatures(item)可用。 getfeatures只是一個實例變量,不是嗎?它似乎被用作一種方法。

docclass.py

class classifier: 
    def __init__(self,getfeatures,filename=None): 
    # Counts of feature/category combinations 
    self.fc={} 
    # Counts of documents in each category 
    self.cc={} 
    self.getfeatures=getfeatures 

    def train(self,item,cat): 
    features=self.getfeatures(item) 
    # Increment the count for every feature with this category 
    for f in features: 
     self.incf(f,cat) 

    # Increment the count for this category 
    self.incc(cat) 
    self.con.commit() 

    def sampletrain(cl): 
    cl.train('Nobody owns the water.','good') 
    cl.train('the quick rabbit jumps fences','good') 
    cl.train('buy pharmaceuticals now','bad') 
    cl.train('make quick money at the online casino','bad') 
    cl.train('the quick brown fox jumps','good') 
+1

這是一個猜測:也許在初始化過程中傳遞的第二個參數是一個函數;儘管它在初始化期間被分配給一個屬性,但可以稍後使用parens調用它。 (這與JavaScript類似,但不是Python。) – Phrogz

+0

@ThiefMaster和steenslag :)只是爲了工作..感謝你的好評。 – zono

+0

@Phrogz'類似於JS'對我來說很容易理解。謝謝 – zono

回答

5

在Python,因爲對於一個方法調用的括號不是可選的,可以參考一種方法和一個方法的調用之間進行區分。即

def example(): 
    pass 

x = example # x is now a reference to the example 
      # method. no invocation takes place 
      # but later the method can be called as 
      # x() 

x = example() # calls example and assigns the return value to x 

因爲對於一個方法調用的括號在Ruby中是可選的,你需要使用例如一些額外的代碼x = method(:example)x.call以實現相同的目的。

+0

謝謝!我會盡量根據你的答案編寫代碼。 – zono

+1

您應該能夠使用上面給出的樣式,或者按照tokland的建議寫'initialize'來接受塊,具體取決於您是否想爲'getfeatures提供一個命名方法或匿名塊功能。如果您需要更多詳情,請告訴我。 – mikej

3

的慣用方式在Ruby中發送行爲(在你的代碼,因爲getfeatures顯然是一個可以調用)是使用塊:

class Classifier 
    def initialize(filename = nil, &getfeatures) 
    @getfeatures = getfeatures 
    ... 
    end 

    def train(item, cat) 
    features = @getfeatures.call(item) 
    ... 
    end 

    ... 
end 

Classifier.new("my_filename") do |item| 
    # use item to build the features (an enumerable, array probably) and return them 
end 
2

如果你從Python的翻譯,你必須學習Python,所以你對不是「完全無知」。沒有捷徑。

+1

是的,你是對的。我將開始學習。 – zono