创建列表时项目数错误

2024-06-26 00:16:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个由元组组成的文档列表,每个元组由一个元组列表和一个字符串组成,所以看起来像这样:

[([('NOUN', 'ADP'), ('ADP', 'NOUN'), ('NOUN', 'PROPN'), ('PROPN', 'ADJ'), ('ADJ', 'DET')], 'M'), 
('NOUN', 'ADP'), ('ADP', 'NOUN'), ('NOUN', 'PROPN'), ('PROPN', 'ADJ'), ('ADJ', 'DET')], 'F'), ...]

我正在使用nltk生成列表:

from nltk.corpus import PlaintextCorpusReader
corpus = PlaintextCorpusReader('C:\CorpusData\Polit_Speeches_by_Gender_POS', '.*\.txt')
documents = [(list(ngrams(corpus.words(fileid), 2)), gender)
    for gender in [f[47] for f in corpus.fileids()]
    for fileid in corpus.fileids()]

问题是,len(corpus.fileids())是84(什么是正确的),但是len(documents)是7056‬. 因此,不知怎的,我设法将文档数平方。我希望清单上只有84项

我注意到{}和{}是相同的(当然{}和{}等也一样)。当然,我可以将7056个项目的完整列表切分,但这并不能解释任何事情。。。我是Python和编程新手,希望您能给予我帮助


Tags: in文档列表forcorpusdocuments元组noun
1条回答
网友
1楼 · 发布于 2024-06-26 00:16:05

如果我正确地阅读了您的程序,那么您正在尝试将每个文档的列表存储在元组中,以及文档的“性别”,即fileid的索引47处的元素

用于构造documents的列表理解首先迭代内部列表理解,然后迭代corpus.fileids()。当Python列表理解迭代两个iterable时,对于第一个iterable的每个值,它将迭代整个第二个iterable。我们可以通过一个例子看到这一点:

>>> print([(a, b) for a in [1, 2] for b in [1, 2]])
[(1, 1), (1, 2), (2, 1), (2, 2)]

相反,在这种情况下,我们似乎可以通过将f[47]应用于我们从corpus.fileids()提取的文件ID来避免双重迭代。这样,每个fileid只考虑一次

documents = [(list(ngrams(corpus.words(fileid), 2)), fileid[47]) for fileid in corpus.fileids()]

因此,整个程序就变得非常简单

from nltk.corpus import PlaintextCorpusReader
corpus = PlaintextCorpusReader('C:\CorpusData\Polit_Speeches_by_Gender_POS', '.*\.txt')
documents = [(list(ngrams(corpus.words(fileid), 2)), fileid[47]) for fileid in corpus.fileids()]

相关问题 更多 >