我有一个包含两列 id
和 text
的数据框
我想添加一个新列,其中包含每行文本的字数。
我创建了一个 userdefinedFunction,其中我从 nltk
实现了
word_tokenizer
和
freqDict
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)
我是一名优秀的程序员,十分优秀!