使用Tokenisers用嵌套循环列表理解迭代2个对象



我正试图从语料库中获取大量数据样本,并确定标记中停止词的比例。

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行,尽管我不确定如何使用两个不同的对象进行迭代,这两个对象都是.isalfa((和stopwwords。

我对您使用的库知之甚少,但对列表理解有所了解。正确的语法是

[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。

只要用if替换and,它就可能工作。嵌套列表理解在其他方面是正确的。我只是不建议元素和可迭代(sentence(使用相同的名称,因为这可能会导致混淆。

最新更新