如何将Python程序移植到Ruby

1 投票
3 回答
690 浏览
提问于 2025-04-17 06:21

我正在尝试把一个Python程序移植到Ruby,但我对Python完全不了解。

你能给我一些建议吗?

我想运行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')

3 个回答

2

如果你想把东西从Python转过来,你得先学会Python,这样你才不会对它“完全无知”。没有什么捷径可走。

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
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,才能达到同样的效果。

撰写回答