【发布时间】:2018-01-03 03:38:03
【问题描述】:
我正在尝试创建一个循环,允许我检索列表中的标记化数据值,检查标记化单元格值中是否有停用词并将其附加到新列表中。
# Importing the packages to be used
import xlrd
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
# Declaration of file path of the data and opening of workbook and worksheet
file_path = "C:/Users/L31101/Documents/Data/Copy_1.xlsx"
workbook = xlrd.open_workbook(file_path)
worksheet = workbook.sheet_by_name("ConsolidateModuleQnComment")
# Grabs the numbers of rows and columns of the worksheet
rowcount = worksheet.nrows
columncount = worksheet.ncols
# Prints the number of row and columns
print("\nRow count: %d" % rowcount)
print("Column count: %d" % columncount)
# Grabbing the cell values and placing them inside an array named data_value
data_value = []
for rowindex in range(2, rowcount):
# print("\nCurrent row number: %d" % rowindex)
# print(worksheet.cell_value(rowindex, 6))
data_value.append(worksheet.cell_value(rowindex, 6))
# Grabbing the values inside data_value cell and tokenizes them, and then adds them into the data_tokenized array
data_tokenized = []
for valueindex in range(0, len(data_value)):
data_tokenized.append(word_tokenize(data_value[valueindex]))
# Grabbing the tokenized values from the data_tokenized array and removing the stopwords
stop_words = set(stopwords.words("english"))
data_stopword_removed = []
for tokenizedindex in range(0, len(data_tokenized)):
if data_tokenized[tokenizedindex] not in stop_words:
data_stopword_removed.append(data_tokenized[tokenizedindex])
print("\nNumber of records: %d" % len(data_stopword_removed))
它给出以下错误消息
C:\Users\L31101\PycharmProjects\Year3\venv\Scripts\python.exe C:/Users/L31101/PycharmProjects/Year3/SentimentAnalysis.py
Row count: 5792
Column count: 7
Traceback (most recent call last):
File "C:/Users/L31101/PycharmProjects/Year3/SentimentAnalysis.py", line 47, in <module>
if test_variable not in stop_words:
TypeError: unhashable type: 'list'
Process finished with exit code 1
有什么办法可以解决这个问题吗?
【问题讨论】:
-
为什么是
test_variable = data_tokenized[1]?1将始终是同一个元素。 -
我试图只用一个变量和一个特定的变量来测试它,因为当我放入一个数组时,它不起作用。我会用我累的第一件事发布其他代码,但是两种方法都不起作用
-
如果您创建Minimal, Complete, and Verifiable 示例,您将获得更多更好的答案。尤其要确保输入和预期数据是完整的(不是伪数据),并且可以轻松剪切并粘贴到编辑器中,以便测试建议的解决方案。
-
您没有显示导致错误的代码。错误在说:
if test_variable not in stop_words:的行上,我在您的代码中看不到该行。无论如何,错误说:您的test_variable,这是一个列表,在这个测试中是不允许的。使用元组或其他可散列类型(例如str、int、bool、tuple...
标签: python list if-statement