2011-11-15 66 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