如何通过阻止嵌套列表中的单词来获取嵌套列表?
How to get a nested list by stemming the words inside the nested lists?
我有一个 Python 列表,其中有几个子列表的标记为 tokens
。
我想阻止其中的标记,以便输出为 stemmed_expected
.
tokens = [['cooked', 'lovely','baked'],['hotel', 'going','liked'],['room','looking']]
stemmed_expected: [['cook', 'love','bake'],['hotel', 'go','like'],['room','look']]
我试过的for循环如下:
from nltk.stem import PorterStemmer
ps = PorterStemmer()
stemmed_actual = []
for m in tokens:
for word in m:
word = ps.stem(word)
stemmed_actual.append(word)
但是这个for循环的输出是:
stemmed_actual = ['cook', 'love', 'bake', 'hotel', 'go', 'like', 'room', 'look']
如何修改 for 循环以获取子列表中的词干词,就像在 stemmed_expected
中一样?
您可以使用嵌套列表理解:
from nltk.stem import PorterStemmer
tokens = [['cooked', 'lovely','baked'],['hotel', 'going','liked'],['room','looking']]
ps = PorterStemmer()
stemmed = [[ps.stem(word) for word in sublst] for sublst in tokens]
print(stemmed)
# [['cook', 'love', 'bake'], ['hotel', 'go', 'like'], ['room', 'look']]
我有一个 Python 列表,其中有几个子列表的标记为 tokens
。
我想阻止其中的标记,以便输出为 stemmed_expected
.
tokens = [['cooked', 'lovely','baked'],['hotel', 'going','liked'],['room','looking']]
stemmed_expected: [['cook', 'love','bake'],['hotel', 'go','like'],['room','look']]
我试过的for循环如下:
from nltk.stem import PorterStemmer
ps = PorterStemmer()
stemmed_actual = []
for m in tokens:
for word in m:
word = ps.stem(word)
stemmed_actual.append(word)
但是这个for循环的输出是:
stemmed_actual = ['cook', 'love', 'bake', 'hotel', 'go', 'like', 'room', 'look']
如何修改 for 循环以获取子列表中的词干词,就像在 stemmed_expected
中一样?
您可以使用嵌套列表理解:
from nltk.stem import PorterStemmer
tokens = [['cooked', 'lovely','baked'],['hotel', 'going','liked'],['room','looking']]
ps = PorterStemmer()
stemmed = [[ps.stem(word) for word in sublst] for sublst in tokens]
print(stemmed)
# [['cook', 'love', 'bake'], ['hotel', 'go', 'like'], ['room', 'look']]