【问题标题】:Create a matplotlib table/graph from NLTK ngrams从 NLTK ngrams 创建一个 matplotlib 表/图
【发布时间】:2022-06-16 03:11:56
【问题描述】:

我使用 NLTK 中的 ngrams 功能为一组产品评论创建了二元组。使用以下代码清理数据并标记文本等:

myDataNeg = df3[df3['sentiment_cat']=='Negative']

# Tokenise each review
myTokensNeg = [word_tokenize(Reviews) for Reviews in myDataNeg['clean_review']]

# Remove stopwords and lowercase all
# Note that len(review)>1 will make sure at least two words are in a review. 
myTokensNeg_noSW_noCase = [[word.lower() for word in Reviews if (len(Reviews)>1) and 
                            (word.lower() not in en_stopwords) and 
                            (len(word)>3)] for Reviews in myTokensNeg]

# Generate lists of bigrams
myBigramNeg = [list(bigrams(Reviews)) for Reviews in myTokensNeg_noSW_noCase]
#myBigramNeg = [list(ngrams(Reviews,n)) for Reviews in myTokensNeg_noSW_noCase]

# Put all lists together
myBigramListNeg = list(itertools.chain.from_iterable(myBigramNeg))


# Get the most frequent ones
bigramFreqNeg = FreqDist(myBigramListNeg)
negbigram = bigramFreqNeg.most_common(5)
negbigram

我的输出显示了最常见的单词对及其频率:

[(('stopped', 'working'), 637),
 (('battery', 'life'), 408),
 (('waste', 'money'), 354),
 (('samsung', 'galaxy'), 322),
 (('apple', 'store'), 289)]

但是我希望能够使用 matplotlib 包将其可视化。我如何制作一个简单的表格或条形图,显示我制作的最常出现的二元组及其频率? 我尝试了下面的代码,但它只返回一个错误:

import matplotlib.pyplot as plt

negbigram.plot.barh(color='blue', width=.9, figsize=(12, 8))

输出:

AttributeError: 'list' object has no attribute 'plot'

对使用 Python 非常陌生,非常感谢任何帮助

提前致谢

【问题讨论】:

    标签: python matplotlib nltk visualization


    【解决方案1】:

    您需要将输出分离到 x 轴和 y 轴

    更多关于plt.brh的信息

    import matplotlib.pyplot as plt
    
    out_ = [
        (('stopped', 'working'), 637),
        (('battery', 'life'), 408),
        (('waste', 'money'), 354),
        (('samsung', 'galaxy'), 322),
        (('apple', 'store'), 289)
    ]
    
    # join the 2 words with '-' in the middle
    wrds = ['-'.join(x) for x, c in out_]
    
    # get the counts
    wdth = [c for x, c in out_]
    
    plt.barh(wrds, wdth, color='blue')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-17
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 2011-02-08
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多