2013-05-16 79 views
0

我有一个Python的问题。 我想了解哪些是存储在我发现是一个生成器的对象中的信息。 我对Python一无所知,但我必须了解这段代码如何工作才能将其转换为Java。 代码如下:python嵌套生成器对象内容

def segment(text): 
    "Return a list of words that is the best segmentation of text." 
    if not text: return [] 
    candidates = ([first]+segment(rem) for first,rem in splits(text)) 
    return max(candidates, key=Pwords) 

def splits(text, L=20): 
    "Return a list of all possible (first, rem) pairs, len(first)<=L." 
    pairs = [(text[:i+1], text[i+1:]) for i in range(min(len(text), L))] 
    return pairs 

def Pwords(words): 
    "The Naive Bayes probability of a sequence of words." 
    productw = 1 
    for w in words: 
     productw = productw * Pw(w) 
    return productw 

,而我的理解是怎么方法Pwords并分割工作(功能Pw的(W)只要从一个矩阵的值),我还是想知道,如何“候选人“对象,在”细分“方法中构建并包含它。 以及“max()”函数如何分析此对象。

我希望有人能帮助我,因为我没有找到任何可行的解决方案来打印此对象。 非常感谢大家。 毛罗。

+0

可能重复替换嵌套发电机[在Python了解发电机?(http://stackoverflow.com/questions/1756096/understanding-generators -in-python)相关问题:[Python yield关键字解释](http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained) – Bakuriu

回答

0

生成器是非常简单的抽象。它看起来像一次性自定义迭代器。

gen = (f(x) for x in data) 

意味着根是迭代器,其中每个下一个值等于其中x为相应的数据

的值f(x)的

嵌套发生器类似于列表理解与小的差异:

  • 它是一次性使用
  • 它不会创建整个序列
  • 代码只在迭代过程中运行

更容易调试你可以尝试用列表理解的

def segment(text): 
    "Return a list of words that is the best segmentation of text." 
    if not text: return [] 
    candidates = [[first]+segment(rem) for first,rem in splits(text)] 
    return max(candidates, key=Pwords) 
+0

非常感谢! 我改变了代码,我开始了解这个列表是如何构建的......;) – Mauro