TypeError:“set”对象不支持在Excel中build立索引
有人能帮我吗? 我有这个错误。 我想循环并将所有的数据从wordnet插入到excel的不同列中。 它将首先阅读有一列的Excel文档。 然后,创build其他excel,并为每个单词生成一行和不同列的同义词。
此代码在一列中生成同义词:
import nltk import xlrd import csv import xlwt import xlsxwriter from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.corpus import wordnet workbook = xlrd.open_workbook('C:\\Users\\runeza\Desktop\database.xlsx') sheet_names = workbook.sheet_names() sheet = workbook.sheet_by_name(sheet_names[0]) wb = xlwt.Workbook() ws = wb.add_sheet("test") for col_idx in range(sheet.ncols): for row_idx in range(sheet.nrows): cell = sheet.cell(row_idx, col_idx).value #read content in column cell synonyms = [] for syn in wordnet.synsets(cell): for l in syn.lemmas(): #print(l.name()) synonyms.append(l.name()) a = set(synonyms) #print (a) ws.write(row_idx, col_idx,",".join(a)) wb.save("sample.xls")
我已经修改了代码,以正确地放置在不同的列中的单词:
import nltk import xlrd import csv import xlwt import xlsxwriter from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.corpus import wordnet workbook = xlrd.open_workbook('C:\\Users\\runeza\Desktop\database.xlsx') sheet_names = workbook.sheet_names() sheet = workbook.sheet_by_name(sheet_names[0]) wb = xlwt.Workbook() ws = wb.add_sheet("test") for col_idx in range(sheet.ncols): for row_idx in range(sheet.nrows): cell = sheet.cell(row_idx, col_idx).value #read content in column cell synonyms = [] for syn in wordnet.synsets(cell): for l in syn.lemmas(): synonyms.append(l.name()) a = set(synonyms) #print (a) for col_idx in range(len(a)): for row_idx in range(len(a[col_idx])): ws.write(col_idx, row_idx, a[col_idx][row_idx]) wb.save("sample.xls")
但它给出了这个错误:
Traceback (most recent call last): File "C:\Users\runeza\Documents\PythonCode\outputfile.py", line 29, in <module> for row_idx in range(len(a[col_idx])): TypeError: 'set' object does not support indexing
这就是我的(C:\ Users \ runeza \ Desktop \ database.xlsx)的样子:
这是我的预期结果:
为了您的需要,我觉得list
将是一个更好的select。 set
对象不支持索引(如[0])。
假设同义词被添加到权利单元格中,您可以执行如下操作:
for col_idx in range(sheet.ncols): for row_idx in range(sheet.nrows): cell = sheet.cell(row_idx, col_idx).value #read content in column cell synonyms = [] for syn in wordnet.synsets(cell): for l in syn.lemmas(): synonyms.append(l.name()) # Making the list elements distinct. synonyms = list(set(synonyms)) for i in range(len(a)): ws.write(row_idx, col_idx+i, synonyms[i]) # Made an edit here. wb.save("sample.xls")