求教报错'dict_keys' object is not subscriptable
各位大佬好!我在做文本词频统计,构建了一个字典“words_report”,想把字典导入到excel中。
遇到的问题是,在命令“ws1.cell(row=i, column='A').value = keys_report”这一行报错'dict_keys' object is not subscriptable,求指导
from openpyxl import Workbook
import openpyxl
import jieba
import re
import os
os.chdir('XXXXXX')
wb = openpyxl.load_workbook('xxxxx.xlsx')
ws = wb.active
words_report = {}
for row in range(2, ws.max_row + 1):
words_deal = re.sub("(.*?)", "", ws['D' + str(row)].value)
words_split = jieba.cut(words_deal)
for word in words_split:
if len(word) >= 2:
if word in words_report:
words_report += 1
else:
words_report.setdefault(word, 1)
wb1 = Workbook()
ws1 = wb1.create_sheet(title='sheet1')
for i in range(1, len(words_report)):
keys_report = words_report.keys()
values_report = words_report.values()
ws1.cell(row=i, column='A').value = keys_report
ws1.cell(row=i, column='B').value = values_report
wb1.save(filename='xxxxx.xlsx')
print('ok') ‘dict_keys’类型的对象不能进行索引操作,原因是dict的value()和key()返回的并不是一个真正的数组,只需要用list()强制转换一下即可:
keys_report = list(words_report.keys())
values_report = list(words_report.values()) 我查资料,d.values和d.keys返回的是一个由 d 字典中每个项的 “值”或 “键” 构成的字典视图对象。这个时候要怎么将其中元素取出来呢?
页:
[1]