【问题标题】:store values from loop in a list of lists or a list of tuples将循环中的值存储在列表列表或元组列表中
【发布时间】:2018-12-08 04:50:24
【问题描述】:

那里!

我尝试输出文本中每个单词的所有可能的词性(pos)。但是,我需要将输出打印为“列表列表”或“元组列表”以供进一步使用。

任何人都可以提供帮助,非常感谢!

import nltk
from nltk.tokenize import word_tokenize

text = "I can answer those question ."     # original text
tokenized_text = word_tokenize(text)       # word tokenization
wsj = nltk.corpus.treebank.tagged_words()  
cfd1 = nltk.ConditionalFreqDist(wsj)       # find all possible pos of each word

i = 0
while i< len(tokenized_text):
    pos_only = list(cfd1[tokenized_text[i]])
    y = pos_only
    print(y)
    i+=1

我的输出是

['NNP', 'PRP']
['MD', 'NN']
['NN', 'VB']
['DT']
['NN', 'VBP', 'VB']
['.']

我的预期输出是

[['NNP', 'PRP'], ['MD', 'NN'], ['NN', 'VB'], ['DT'], ['NN', 'VBP', 'VB'], ['.']]

[('NNP', 'PRP'), ('MD', 'NN'), ('NN', 'VB'), ('DT'), ('NN', 'VBP', 'VB'), ('.')]

【问题讨论】:

    标签: list loops while-loop tuples output


    【解决方案1】:

    我认为您需要在迭代期间创建一个空列表并附加元素。我假设print(y) 输出['NNP', 'PRP'] 等。然后您应该将y 转换为元组并在迭代期间将其附加到列表中。这段代码应该可以做到。

    alist = []
    i = 0
    while i < len(tokenized_text):
        pos_only = list(cfd1[tokenized_text[i]])
        y = pos_only
        alist.append(tuple(y))
        i += 1
    print(alist)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 2021-10-11
      相关资源
      最近更新 更多