如何将Python程序移植到Ruby中

2024-10-03 17:18:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个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')

Tags: the方法selfforcldeftrainquick
3条回答

如果你是从Python翻译的,你必须学习Python,这样你对Python“一无所知”。没有捷径。在

在Ruby中发送行为的惯用方法是使用块:

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

在Python中,由于方法调用的方括号不是可选的,所以可以区分方法的引用和方法的调用。i、 e

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()

对比

^{pr2}$

因为方法调用的方括号在Ruby中是可选的,所以需要使用一些额外的代码,例如x = method(:example)和{}来实现相同的功能。在

相关问题 更多 >