CSV文件生成词云效果

词云文件修改

import csv
from wordcloud import WordCloud
import jieba
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image

def reader_file():
    items = []
    with open('C:\\Users\\75930\\Desktop\\basketball\data\\csv\\playername.csv', 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        for i in reader:
            items.append(i)
    f.close()
    return items


items = reader_file()
string = ''
for item in items:
    string = string + item[1]
string = ' '.join(jieba.cut(string))
img = Image.open('./static/image/heart.png')
img_array = np.array(img)
wc = WordCloud(
    background_color='white',
    mask=img_array,
    font_path='msyh.ttc'
)
wc.generate_from_text(string)
fig = plt.figure(figsize=(3.5,3.0))
plt.imshow(wc)
plt.margins(0, 0)
plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
plt.axis('off')
# plt.show()
plt.savefig('./static/image/heart_cloud.png')

这是我找到的一个词云文件,当我用我自己的文件时

布莱克尼
皮特森
多米尼克-琼斯
杰曼
马尚-布鲁克斯
吉伦沃特
萨林杰
王哲林
费尔德
弗格
高登
马兰
布兰登-杰弗森
布兰登-泰勒
阿丘尔
特林布尔
张帆
里斯
林庭谦
姜宇星


报错


```python
Traceback (most recent call last):
  File "C:\Users\75930\Desktop\basketball\plant.py", line 21, in <module>
    string = string + item[1]
IndexError: list index out of range

```

该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:
根据报错信息,可以看出是因为访问了一个空列表或者是一个没有足够元素的列表的问题。在你提供的代码中,出现了 IndexError: list index out of range 的错误,可能是因为读取的 CSV 文件中某一行没有足够的元素导致的。

可以在代码中增加一些判断来避免这个问题,例如加入以下代码:

for item in items:
    if len(item) > 1:
        string = string + item[1]

这样,当读取到的某一行元素数量小于 2 时,就不会执行 string = string + item[1] 的操作,避免了 IndexError 的出现。

另外,还可以对 CSV 文件进行检查,确保其中每一行都有足够的元素,以避免类似的问题。可以使用 Excel 等工具打开 CSV 文件进行检查和编辑,或者使用 Python 中的 csv 模块对文件进行处理和修改。


如果以上回答对您有所帮助,点击一下采纳该答案~谢谢