gpt4 book ai didi

python - 如何从 nltk 中的 freqDist 获取元组列表

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:09 25 4
gpt4 key购买 nike

我有一个包含两列 idtext 的数据框

我想添加一个新列,其中包含每行文本的字数。

我创建了一个 userdefinedFunction,其中我从 nltk

实现了 word_tokenizerfreqDict
word = f.udf(lambda token: word_count)

def word_count(token):
freq_dict = nltk.probability.FreqDist(token)
return [(word, freq) for word, freq in freq_dict.most_common()]

df = df.withColumn('wordcount',word(nltk.word_tokenize(df['text']))

在 tokenizer 之后,我调用了 word_count 并希望获得包含单词及其频率的元组列表。而是在列中得到这个

[[Ljava.lang.Object;@9b4c4d5, [Ljava.lang.Object;@6a5d7d39, ...

最佳答案

您需要为 UDF 指定返回类型。像这样定义一个模式

schema = ArrayType(StructType([StructField("word",StringType(), True), StructField("freq",LongType(), True)]))

并将udf更改为

f.udf(word_count, schema)

关于python - 如何从 nltk 中的 freqDist 获取元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259657/

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