繁体   English   中英

如何将Python程序移植到Ruby

[英]How to port a Python program to Ruby

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

在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来实现相同的目的。

在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

如果您要从Python进行翻译,则必须学习Python,这样您就不会对它“完全一无所知”。 没有捷径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM