我对python很新.我无法弄清楚这个bug.我想用NLTK提取名词.
我写了以下代码:
import nltk
sentence = "At eight o'clock on Thursday film morning word line test best beautiful Ram Aaron design"
tokens = nltk.word_tokenize(sentence)
tagged = nltk.pos_tag(tokens)
length = len(tagged) - 1
a = list()
for i in (0,length):
    log = (tagged[i][1][0] == 'N')
    if log == True:
      a.append(tagged[i][0])
当我运行它时,'a'只有一个元素
a
['detail']
我不懂为什么?
当我在没有for循环的情况下执行它时,它正在运行
log = (tagged[i][1][0] == 'N')
    if log == True:
      a.append(tagged[i][0])
通过手动将"i"的值从0更改为"length",我得到了完美的输出,但是对于for循环,它只返回end元素.有人能告诉我for循环发生了什么问题.
代码后'a'应如下所示
['Thursday', 'film', 'morning', 'word', 'line', 'test', 'Ram' 'Aaron', 'design']
for i in (0,length):
这会迭代两个元素,零和length.如果要迭代零之间的每个数字length,请使用range.
for i in range(0, length):
更好的是,直接迭代序列的元素而不是其索引更为惯用.这将减少像上面那样的拼写错误的可能性.
for item in tagged:
    if item[1][0] == 'N':
      a.append(item[0])
注重尺寸的用户甚至可能更喜欢单行列表理解:
a = [item[0] for item in tagged if item[1][0] == 'N']
>>> from nltk import word_tokenize, pos_tag
>>> sentence = "At eight o'clock on Thursday film morning word line test best beautiful Ram Aaron design"
>>> nouns = [token for token, pos in pos_tag(word_tokenize(sentence)) if pos.startswith('N')]
>>> nouns
['Thursday', 'film', 'morning', 'word', 'line', 'test', 'Ram', 'Aaron', 'design']