我有一个excel数据集,其中包含用户类型、ID和属性描述。我在dataframe(df)的python大熊猫中导入了这个文件。
现在我想把内容分成一个字,两个字,三个字。我可以在NLTK库的帮助下完成一个单词的标记。但我被两个和三个字标记卡住了。例如,列Description
中的一行有句-
孟买主干道上一套全新的住宅公寓,配有便携水。
我想把这句话分割成
"A品牌“、”全新“、”新住宅“、”住宅公寓“.”便携式水“。
这种分裂应该反映在该列的每一行中。
发布于 2017-08-24 19:42:10
下面是一个使用来自ngrams
的nltk
的小例子。希望它有帮助:
from nltk.util import ngrams
from nltk import word_tokenize
# Creating test dataframe
df = pd.DataFrame({'text': ['my first sentence',
'this is the second sentence',
'third sent of the dataframe']})
print(df)
输入dataframe
text
0 my first sentence
1 this is the second sentence
2 third sent of the dataframe
现在,我们可以将ngram与word_tokenize
一起用于bigrams
和trigrams
,并将其应用于数据each的每一行。对于bigram,我们将2
的值与符号化的单词一起传递给ngram函数,而3
的值则是传递给trigram的。ngrams
返回的结果为generator
类型,因此将其转换为list。对于每一行,bigrams
和trigrams
列表都保存在不同的列中。
df['bigram'] = df['text'].apply(lambda row: list(ngrams(word_tokenize(row), 2)))
df['trigram'] = df['text'].apply(lambda row: list(ngrams(word_tokenize(row), 3)))
print(df)
结果:
text \
0 my first sentence
1 this is the second sentence
2 third sent of the dataframe
bigram \
0 [(my, first), (first, sentence)]
1 [(this, is), (is, the), (the, second), (second, sentence)]
2 [(third, sent), (sent, of), (of, the), (the, dataframe)]
trigram
0 [(my, first, sentence)]
1 [(this, is, the), (is, the, second), (the, second, sentence)]
2 [(third, sent, of), (sent, of, the), (of, the, dataframe)]
https://stackoverflow.com/questions/45869287
复制相似问题