我目前正在学习Python中的NLP,并且遇到了Python语法问题。
cfd = nltk.ConditionalFreqDist( #create conditional freq dist
(target, fileid[:4]) #create target (Y) and years (X)
for fileid in inaugural.fileids() #loop through all fileids
for w in inaugural.words(fileid) #loop through each word of each fileids
for target in ['america','citizen'] #loop through target
if w.lower().startswith(target)) #if w.lower() starts with target words
cfd.plot() # plot it
我不明白第2行的目的。而且,我不明白为什么每个循环都不能像Python中的任何循环一样以“:”结尾。
有人可以向我解释此代码吗?该代码有效,但我不完全了解其语法。
谢谢
的自变量nltk.ConditionalFreqDist
是生成器表达式。
语法类似于列表理解的语法:我们可以使用
[(target, fileid[:4]) for fileid in inaugural.fileids()
for w in inaugural.words(fileid)
for target in ['america','citizen']
if w.lower().startswith(target) ]
并将其传递给函数,但是使用生成器可以提高内存效率,因为我们无需在迭代之前构建整个列表。相反,在迭代生成器对象时,(target,...)元组会一一生成。
您还可以查看生成器理解到底如何工作?有关生成器表达式的更多信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句