我想从数据框中提取名词。只有名词。 我这样做
noun
0 day
1 night
我想要
df['noun'] = df.apply(lambda row: nltk.word_tokenize(row['noun']), axis=1)
noun=[]
for index, row in df.iterrows():
noun.append([word for word,pos in pos_tag(row) if pos == 'NN'])
df['noun'] = noun
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-194-688cfbb21ec5> in <module>()
1 noun=[]
2 for index, row in df.iterrows():
----> 3 noun.append([word for word,pos in pos_tag(row) if pos == 'NN'])
4 df['noun'] = noun
C:\Users\Edward\Anaconda3\lib\site-packages\nltk\tag\__init__.py in pos_tag(tokens, tagset)
109 """
110 tagger = PerceptronTagger()
--> 111 return _pos_tag(tokens, tagset, tagger)
112
113
C:\Users\Edward\Anaconda3\lib\site-packages\nltk\tag\__init__.py in _pos_tag(tokens, tagset, tagger)
80
81 def _pos_tag(tokens, tagset, tagger):
---> 82 tagged_tokens = tagger.tag(tokens)
83 if tagset:
84 tagged_tokens = [(token, map_tag('en-ptb', tagset, tag)) for (token, tag) in tagged_tokens]
C:\Users\Edward\Anaconda3\lib\site-packages\nltk\tag\perceptron.py in tag(self, tokens)
150 output = []
151
--> 152 context = self.START + [self.normalize(w) for w in tokens] + self.END
153 for i, word in enumerate(tokens):
154 tag = self.tagdict.get(word)
C:\Users\Edward\Anaconda3\lib\site-packages\nltk\tag\perceptron.py in <listcomp>(.0)
150 output = []
151
--> 152 context = self.START + [self.normalize(w) for w in tokens] + self.END
153 for i, word in enumerate(tokens):
154 tag = self.tagdict.get(word)
C:\Users\Edward\Anaconda3\lib\site-packages\nltk\tag\perceptron.py in normalize(self, word)
222 if '-' in word and word[0] != '-':
223 return '!HYPHEN'
--> 224 elif word.isdigit() and len(word) == 4:
225 return '!YEAR'
226 elif word[0].isdigit():
AttributeError: 'list' object has no attribute 'isdigit'
我的代码
Get-Partition -DiskNumber 1 | Where-Object -FilterScript {$_.Type -Eq "Basic"} |
Set-Partition -NewDriveLetter E
请帮忙,如何改进? *对不起,我已经写了一些文字,以便我可以插入所有追溯 我猜测问题是我无法将列表转换为所需的格式?
答案 0 :(得分:2)
问题在于,在你的循环中,row
是一个pandas Series
而不是列表。您可以通过编写row[0]
来访问单词列表:
>>> for index, row in df.iterrows():
>>> noun.append([word for word,pos in pos_tag(row[0]) if pos == 'NN'])
>>> print(noun)
[['day'], ['night']]
在这里,您将获得一个列表列表,每个列表包含一个句子中的名词。如果您确实需要一个平面列表(如问题中的示例结果),请写下noun.extend(...)
而不是noun.append
。