oppenai.eth

oppenai.eth

Freedom is life.

使用Python可以通过wordcloud库生成词云。

How to generate word clouds using Python and wordcloud, and what to do if you encounter TrueType font recognition issues during the process.

1. Environment Installation#

pip3 install wordcloud

2. Code Demo#

import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# Read data
def read_data(filename):
    df = pd.read_excel(filename)
    return df['Keyword'].tolist()

# Analyze data
def analyze_data(keywords):
    df = pd.DataFrame(keywords, columns=['Keyword'])
    keyword_counts = df['Keyword'].value_counts()

    # Generate word cloud
    wordcloud = WordCloud(width=800, height=400, font_path='/System/Library/Fonts/Supplemental/Arial.ttf').generate_from_frequencies(keyword_counts)
    plt.figure(figsize=(20, 10))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.show()

# Main program
def main():
    keywords = read_data('keywords.xlsx')
    analyze_data(keywords)

if __name__ == '__main__':
    main()

This code reads keywords from an Excel file and uses the WordCloud library to generate a word cloud chart. Finally, the chart is displayed using the Matplotlib library. The read_data() function reads the keywords from the Excel file, the analyze_data() function analyzes the read keywords and generates the corresponding word cloud chart, and the main() function is the main program entry point, which calls the read_data() and analyze_data() functions to implement the entire process from data reading to word cloud chart generation.

*Excel file format:

截屏 2023-05-19 12.34.19

3. Font Issue#

I am using a Mac, and when generating the word cloud, I kept getting the error message: ValueError: Only supported for TrueType fonts, indicating that only TrueType fonts are supported. However, I am already using a TrueType font. In this case, you just need to check if the font file path is correct.

pip install --upgrade pillow

This error may be caused by the version of the Pillow library (PIL). In some versions of the Pillow library, the ImageDraw.textbbox method only supports TrueType fonts and does not support OpenType fonts. Even if you provide a TrueType font file, Pillow may not be able to recognize it correctly.

4. Display#

截屏 2023-05-19 12.33.13

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。