python - NLTK ConditionalFreqDist 到 Pandas 数据帧

标签 python pandas nltk

我正在尝试使用 nltk.ConditionalFreqDist 生成的表,但我似乎找不到任何关于将表写入 csv 文件或导出为其他格式的文档。我喜欢在 pandas 数据框对象中使用它,这也很容易写入 csv。我能找到的唯一推荐的帖子 pickling the CFD object这并不能真正解决我的问题。

我编写了以下函数将 nltk.ConditionalFreqDist 对象转换为 pd.DataFrame:

def nltk_cfd_to_pd_dataframe(cfd):
    """ Converts an nltk.ConditionalFreqDist object into a pandas DataFrame object. """

    df = pd.DataFrame()
    for cond in cfd.conditions():
        col = pd.DataFrame(pd.Series(dict(cfd[cond])))
        col.columns = [cond]
        df = df.join(col, how = 'outer')

    df = df.fillna(0)

    return df

但如果我要这样做,也许首先编写一个生成 pd.DataFrame 的新 ConditionalFreqDist 函数是有意义的。但在我重新发明轮子之前,我想看看是否有任何我遗漏的技巧 - 在 NLTK 或其他地方使 ConditionalFreqDist 对象与其他格式对话,最重要的是将其导出到 csv 文件。

谢谢。

最佳答案

pd.DataFrame(freq_dist.items(), columns=['word', 'frequency'])

关于python - NLTK ConditionalFreqDist 到 Pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15145172/

相关文章:

python-3.x - 使用 if 语句在 pandas 中创建新列

pandas - Facebook NeuralProphet - 生成模型文件

python - 从字符串中获取所有可能的英文单词

python - 在 Pandas Merge 上放置 WHERE 子句

python - 如何使用 factorplot 用分类值注释条形图或绘制 4 个变量?

python - Mongoengine Transactions怎么来的?

python - NLTK 上下文无关文法生成器

python - python中区分乱码/错误和外来词/名称的算法或工具?

python - 从列中选取值

python - 将长数据帧转换为宽数据帧