GeoLLM / revision /test.py
Pengfa Li
Upload folder using huggingface_hub
badcf3c verified
import json
import wordcloud
import matplotlib.pyplot as plt
import os
# 从JSON文件读取词频数据
with open('./word_frequency.json', 'r', encoding='utf-8') as f:
word_freq = json.load(f)
# 尝试使用不同的中文字体
def get_chinese_font():
# 常见的Windows中文字体路径
font_paths = [
"C:/Windows/Fonts/simhei.ttf", # 黑体
"C:/Windows/Fonts/simsun.ttc", # 宋体
"C:/Windows/Fonts/msyh.ttc", # 微软雅黑
"C:/Windows/Fonts/SIMKAI.TTF", # 楷体
"E:/Downloads/times+simsun.ttf", # 你原来的字体
]
for font_path in font_paths:
if os.path.exists(font_path):
print(f"使用字体: {font_path}")
return font_path
print("未找到合适的中文字体,将使用默认字体(可能无法正确显示中文)")
return None
# 获取可用的中文字体
chinese_font = get_chinese_font()
# 创建词云对象
wc = wordcloud.WordCloud(
font_path=chinese_font, # 使用检测到的字体
background_color="white", # 指定背景颜色
max_words=200, # 词云显示的最大词数
max_font_size=255, # 指定最大字号
width=800, # 增加宽度
height=600, # 增加高度
# mask=mask
)
try:
# 使用词频字典生成词云
wc = wc.generate_from_frequencies(word_freq)
plt.figure(figsize=(10, 8)) # 设置图片大小
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()
# 可选:保存词云图片
# wc.to_file("wordcloud.png")
except Exception as e:
print(f"生成词云时出错: {e}")
print("尝试使用默认设置...")
# 如果出错,尝试不使用字体
wc_default = wordcloud.WordCloud(
background_color="white",
max_words=200,
max_font_size=255,
width=800,
height=600
)
wc_default = wc_default.generate_from_frequencies(word_freq)
plt.figure(figsize=(10, 8))
plt.imshow(wc_default, interpolation='bilinear')
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()
"""Wordcloud详细参数设置
def __init__(self, font_path=None, width=400, height=200, margin=2,
ranks_only=None, prefer_horizontal=.9, mask=None, scale=1,
color_func=None, max_words=200, min_font_size=4,
stopwords=None, random_state=None, background_color='black',
max_font_size=None, font_step=1, mode="RGB",
relative_scaling='auto', regexp=None, collocations=True,
colormap=None, normalize_plurals=True, contour_width=0,
contour_color='black', repeat=False,
include_numbers=False, min_word_length=0):
"""