gpt4 book ai didi

python - 如何在数据框中使用 word_tokenize

转载 作者:太空狗 更新时间:2023-10-29 19:31:06 28 4
gpt4 key购买 nike

我最近开始使用 nltk 模块进行文本分析。我被困在一个点上。我想在数据帧上使用 word_tokenize,以获得数据帧特定行中使用的所有单词。

data example:
text
1. This is a very good site. I will recommend it to others.
2. Can you please give me a call at 9983938428. have issues with the listings.
3. good work! keep it up
4. not a very helpful site in finding home decor.

expected output:

1. 'This','is','a','very','good','site','.','I','will','recommend','it','to','others','.'
2. 'Can','you','please','give','me','a','call','at','9983938428','.','have','issues','with','the','listings'
3. 'good','work','!','keep','it','up'
4. 'not','a','very','helpful','site','in','finding','home','decor'

基本上,我想分离所有单词并找到数据框中每个文本的长度。

我知道 word_tokenize 可以用于字符串,但如何将它应用于整个数据框?

请帮忙!

提前致谢...

最佳答案

您可以使用 DataFrame API 的apply方法:

import pandas as pd
import nltk

df = pd.DataFrame({'sentences': ['This is a very good site. I will recommend it to others.', 'Can you please give me a call at 9983938428. have issues with the listings.', 'good work! keep it up']})
df['tokenized_sents'] = df.apply(lambda row: nltk.word_tokenize(row['sentences']), axis=1)

输出:

>>> df
sentences \
0 This is a very good site. I will recommend it ...
1 Can you please give me a call at 9983938428. h...
2 good work! keep it up

tokenized_sents
0 [This, is, a, very, good, site, ., I, will, re...
1 [Can, you, please, give, me, a, call, at, 9983...
2 [good, work, !, keep, it, up]

要找到每个文本的长度,请再次尝试使用 applylambda 函数:

df['sents_length'] = df.apply(lambda row: len(row['tokenized_sents']), axis=1)

>>> df
sentences \
0 This is a very good site. I will recommend it ...
1 Can you please give me a call at 9983938428. h...
2 good work! keep it up

tokenized_sents sents_length
0 [This, is, a, very, good, site, ., I, will, re... 14
1 [Can, you, please, give, me, a, call, at, 9983... 15
2 [good, work, !, keep, it, up] 6

关于python - 如何在数据框中使用 word_tokenize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33098040/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com