使用wordcloud时明明是字符串格式却遇到TypeError: expected string or bytes-like object

使用wordcloud时明明是字符串格式却遇到TypeError: expected string or bytes-like object

困扰了上午两小时的问题,下午五分钟想到原因,果然debug遇到问题不如歇一歇调个状态,还是记录一下吧,万一有和我一样的呢对吧

今天做一个词云的时候遇到的问题
原代码是:

def wordcloud(sorted_news):
    str = f'{today_str},' + ",".join([k for k, v in sorted_news.items()])
    sentence_seged = jieba.lcut(str)
    swords = stopwords()
    jieba_text = []
    for word in sentence_seged:
        if word not in swords:
            jieba_text.append(word)
    wd_join_text = " ".join(jieba_text)
    mask = np.array(Image.open("./weibo.png"))
    wc = WordCloud(font_path="msyh.ttf", width=1600, height=900, mask=mask).generate_from_text(wd_join_text)
    #...以下省略

然后哩,就在最后这行遇到了TypeError: expected string or bytes-like object,我检查反复思考,以为是wordcloud库的版本问题,查找资料后又发现没啥问题,于是我迷惑了
晚上又打开电脑,仔细检查报错的追踪路径和代码,发现:

Traceback (most recent call last):
  File "***.py", line 151, in <module>
    wordcloud(sorted_news)
  File "***.py", line 119, in wordcloud
    wc = WordCloud(font_path="msyh.ttf", width=1600, height=900, mask=mask).generate(wd_join_text)
  File "D:\download\anaconda\lib\site-packages\wordcloud\wordcloud.py", line 632, in generate
    return self.generate_from_text(text)
  File "D:\download\anaconda\lib\site-packages\wordcloud\wordcloud.py", line 614, in generate_from_text
    self.generate_from_frequencies(words)
  File "D:\download\anaconda\lib\site-packages\wordcloud\wordcloud.py", line 446, in generate_from_frequencies
    self.generate_from_frequencies(dict(frequencies[:2]),
    font = ImageFont.truetype(self.font_path, font_size)
  File "D:\download\anaconda\lib\site-packages\PIL\ImageFont.py", line 853, in truetype
    return freetype(font)
  File "D:\download\anaconda\lib\site-packages\PIL\ImageFont.py", line 850, in freetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
  File "D:\download\anaconda\lib\site-packages\PIL\ImageFont.py", line 173, in __init__
    freetype_version = parse_version(features.version_module("freetype2"))
  File "D:\download\anaconda\lib\site-packages\packaging\version.py", line 57, in parse
    return Version(version)
  File "D:\download\anaconda\lib\site-packages\packaging\version.py", line 296, in __init__
    match = self._regex.search(version)
TypeError: expected string or bytes-like object

看朋友们,从wordcloud的路径找到了PIL的路径,找到了ImageFont的问题,然后到了version的问题,所以我终于怀疑到了PIL库的问题,一查,真是
附一个参考链接:PIL在win10中引用字体文件时报错TypeError: expected string or bytes-like object
在这里感谢博主

在下载8.3.1版本时又遇到问题,pip install pillow==8.3.1太慢了,于是换个国内镜像进行下载

pip install pillow -i https://mirrors.aliyun.com/pypi/simple

再附一个参考链接:Python安装pillow(3.8.1版本)

大功告成!!
使用wordcloud时明明是字符串格式却遇到TypeError: expected string or bytes-like object_第1张图片

你可能感兴趣的:(python,python)