我正试图从语料库中获取大量数据样本,并确定令牌的比例是停用词。
from sussex_nltk.corpus_readers import MedlineCorpusReader
from nltk.corpus import stopwords
mcr = MedlineCorpusReader()
sample_size = 10000
stopwords = stopwords.words('english')
raw_sentences = mcr.sample_raw_sents(sample_size)
tokenised_sentences = [word_tokenize(sentence) for sentence in raw_sentences]
filter_tok=[[sentence.isalpha() for sentence in sentence and sentence not in stopwords] for sentence in tokenised_sentences]
raw_vocab_size = vocabulary_size(tokenised_sentences)
filter_vocab_size = vocabulary_size(filter_tok)
print("Stopwords produced a {0:.2f}% reduction in vocabulary size from {1} to {2}".format(
100*(raw_vocab_size - filter_vocab_size)/raw_vocab_size,raw_vocab_size,filter_vocab_size))
尽管即使我标记了清单之后,我仍然似乎无法遍历清单。相信问题根源于第11行,尽管我不确定如何使用.isalpha()和停用词这两个不同的对象进行迭代。
答案 0 :(得分:2)
我对您正在使用的库知之甚少,但对列表理解却有所了解。正确的语法是
[element for element in iterable if condition]
但是你用过
[element for element in iterable and condition]
因此Python将iterable and condition
(或在您的示例sentence and sentence not in stopwords
中)解释为一个表达式。结果是一个布尔值且不可迭代,因此会引发TypeError。
只需将and
替换为if
,它可能会起作用。嵌套列表推导在其他方面是正确的。我只是不建议为元素和可迭代(sentence
)使用相同的名称,因为这可能导致混乱。