python出现关于Os问题

import re
from wordcloud import WordCloud
import jieba
with open('test.txt','r',encoding='utf-8')as f:
    text=f.read()
print(text)
words=[word for word in jieba.cut(text) if re.search(r'[\u4e00-\u9fa5]+',word)]
words=[word for word in jieba.cut(text) if re.search(r'[a-zA-z]+',word)]
w=WordCloud(
    background_color='white',
    max_words=100,
    font_path='C:\\Users\\benson\\Desktop\\Python新课\\test.txt',
    height=10,
    width=10,
    max_font_size=90,
    random_state=10,
)
myword=w.generate(text)
w.to_file('signature.png')
print(words)

上面的是代码,下面是问题

Traceback (most recent call last):
  File "C:\Users\benson\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 204, in __init__
    font_bytes_path.decode("ascii")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 30: ordinal not in range(128)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/benson/Desktop/Python新课/2021.9.5.py", line 18, in <module>
    myword=w.generate(text)
  File "C:\Users\benson\AppData\Local\Programs\Python\Python37\lib\site-packages\wordcloud\wordcloud.py", line 632, in generate
    return self.generate_from_text(text)
  File "C:\Users\benson\AppData\Local\Programs\Python\Python37\lib\site-packages\wordcloud\wordcloud.py", line 614, in generate_from_text
    self.generate_from_frequencies(words)
  File "C:\Users\benson\AppData\Local\Programs\Python\Python37\lib\site-packages\wordcloud\wordcloud.py", line 496, in generate_from_frequencies
    font = ImageFont.truetype(self.font_path, font_size)
  File "C:\Users\benson\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 855, in truetype
    return freetype(font)
  File "C:\Users\benson\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 852, in freetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
  File "C:\Users\benson\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 209, in __init__
    load_from_bytes(f)
  File "C:\Users\benson\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 197, in load_from_bytes
    "", size, index, encoding, self.font_bytes, layout_engine
OSError: invalid stream operation

Process finished with exit code 1


请求帮助,谢谢

看报错信息,真正报错的是18行,字符集编码的问题

img

试试在文章开头设置:

import sys
reload(sys)
sys.setdefaultencoding('utf8')