TypeError:“set”对象不支持在ex中编制索引

2024-03-28 13:15:46 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我吗?我有这个错误。我想把wordnet的所有数据循环插入excel的不同列中。它将首先读取一个只有一列的excel文档。然后,它将创建另一个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")

我修改了代码,将单词正确地放在不同的列中:

^{pr2}$

但它给出了一个错误:

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\数据库.xlsx)外观:

existing sheet

这是我预期的结果:

enter image description here


Tags: infromimportforcellcolexcelusers
1条回答
网友
1楼 · 发布于 2024-03-28 13:15:46

根据您的需要,我认为list将是一个更好的选择。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")

相关问题 更多 >