为什么ConditionalFreqDist在NLTK中不起作用?

时间:2015-09-28 13:08:01

标签: python-2.7 nltk

cfd = nltk.ConditionalFreqDist(
    (target,fileid[:4])
    for target in ['america']
    for fileid in inaugural.fileids()

它工作正常,但我不知道为什么样本在每个文件中都有1个?

1 个答案:

答案 0 :(得分:0)

这与FreqDist无关。这是关于你喂它的东西 - 你需要知道generator expressions是如何工作的。

在你的情况下,它是一个双向嵌套生成器。看它就像一个for循环:

for target in ['america']:
    for fileid in inaugural.fileids():
        # do something with target and fileid

在这种情况下,“做某事”部分只是向FreqDist添加一对字符串。字符串对看起来像这样:

('america', <prefix_of_file_1>)
('america', <prefix_of_file_2>)
('america', <prefix_of_file_3>)
...

第一个元素始终相同,因为目标列表中只有一个项目。第二个元素由文件ID的前4个字符组成。 每个文件只有一个条目,,无论文件中是否包含“美国”,因为您不查看文件的内容,只需迭代文件ID。

这样做的方法就像原始帖子中的第一个例子,在你删除它之前:

cfd = nltk.ConditionalFreqDist(
    (target, fileid[:4])
    for target in ['america']
    for fileid in inaugural.fileids()
    for w in inaugural.words(fileid)
    if w.lower().startswith(target))

让我们看看这个三个 -way嵌套的生成器表达式,写成for循环:

for target in ['america']:
    for fileid in inaugural.fileids():
        for w in inaugural.words(fileid):
            if w.lower().startswith(target)):
                # add target and fileid[:4] to the FreqDist

所以在这里你在每个文件(中间循环)中迭代所有单词(最里面的循环),然后你为每个目标(第一个循环;这里只有一个,所以没有太多)循环)。然后你跳过所有不以“美国”开头的单词。

例如,假设文件1出现两次“America”(或“American”),第二个文件没有提及目标,第三个文件有3次出现。然后添加到FreqDist的对将如下所示:

('america', <prefix_of_file_1>)
('america', <prefix_of_file_1>)
('america', <prefix_of_file_3>)
('america', <prefix_of_file_3>)
('america', <prefix_of_file_3>)
...

因此,对于目标的每次出现,都会为FreqDist提供一个计数条目。没有出现的文件不计算,多次出现多次计数。

相关问题