NLTK的一些问题

时间:2013-01-22 16:31:20

标签: python tokenize nltk counting corpus

我对Python和NLTK很新,但我有一个问题。 我正在写一些东西,只从自制的语料库中提取超过7个字符的单词。但事实证明它提取了每一个字...... 谁知道我做错了什么?

loc="C:\Users\Dell\Desktop\CORPUS"
Corpus= CategorizedPlaintextCorpusReader(loc,'(?!\.svn).*\.txt, cat_pattern=r '(Shakespeare|Milton)/.*)
def long_words(corpus)
    for cat in corpus.categories():
        fileids=corpus.fileids(categories=cat)
        words=corpus.words(fileids)
         long_tokens=[]
         words2=set(words)
         if len(words2) >=7:
             long_tokens.append(words2)


Print long_tokens

谢谢大家!

1 个答案:

答案 0 :(得分:1)

替换

if len(words2) >=7:
    long_tokens.append(words2)

使用:

long_tokens += [w for w in words2 if len(w) >= 7]

说明:如果单词的数量至少为7(所以我想总是为你的语料库),你正在追加corpus.words(fileids)生成的所有单词(标记)。你真正想做的是从标记集中过滤掉短于7个字符的单词,并将剩余的长单词追加到long_tokens

您的函数应返回结果 - 包含7个字符或更多字符的标记。我假设你创建和处理CategorizedPlaintextCorpusReader的方式还可以:

loc="C:\Users\Dell\Desktop\CORPUS"
Corpus= CategorizedPlaintextCorpusReader(loc,'(?!\.svn).*\.txt, cat_pattern=r'(Shakespeare|Milton)/.*)

def long_words(corpus = Corpus):
    long_tokens=[]
    for cat in corpus.categories():
        fileids = corpus.fileids(categories=cat)
        words = corpus.words(fileids)
        long_tokens += [w for w in set(words) if len(w) >= 7]
    return set(long_tokens)

print "\n".join(long_words())

以下是您在评论中提出的问题的答案:

for loc in ['cat1','cat2']:
  print len(long_words(corpus=CategorizedPlaintextCorpusReader(loc,'(?!\.svn).*\.txt, cat_pattern=r'(Shakespeare|Milton)/.*)), 'words over 7 in', loc