Python TypeError:在Windows 10上,列表索引必须是整数或片,而不是str
我试图找出福尔摩斯故事列表的逆文档频率。请看一下代码: 反向文档频率是一个词在多个文档中的常见或罕见程度的度量 因此,这意味着反向文档频率或简称为Python TypeError:在Windows 10上,列表索引必须是整数或片,而不是str,python,artificial-intelligence,nltk,frequency,word-frequency,Python,Artificial Intelligence,Nltk,Frequency,Word Frequency,我试图找出福尔摩斯故事列表的逆文档频率。请看一下代码: 反向文档频率是一个词在多个文档中的常见或罕见程度的度量 因此,这意味着反向文档频率或简称为idf,衡量一个单词在特定文档中的常见程度,而在其他文档中并不常见 idf的公式为: 日志x(文档总数/包含的文档数量(word)) main.py import math import nltk import os import sys def main(): if len(sys.argv) != 2: sys.exi
idf
,衡量一个单词在特定文档中的常见程度,而在其他文档中并不常见
idf的公式为:
日志x(文档总数/包含的文档数量(word))
main.py
import math
import nltk
import os
import sys
def main():
if len(sys.argv) != 2:
sys.exit("Usage: python main.py corpus")
print("Loading data...")
corpus = load_data(sys.argv[1])
words = set()
for filename in corpus:
words.update(corpus[filename])
idfs = list()
for word in words:
f = sum(word in corpus[filename] for filename in corpus)
idf = math.log(len(corpus) / f)
idfs[word] = idf
tfidfs = dict()
for filename in corpus:
tfidfs[filename] = []
for word in corpus[filename]:
tf = corpus[filename][word]
tfidfs[filename].append((word, tf * idfs[word]))
for filename in corpus:
tfidfs[filename].sort(key=lambda tfidf: tfidf[1], reverse=True)
tfidfs[filename] = tfidfs[filename][:5]
print()
for filename in corpus:
print(filename)
for term, score in tfidfs[filename]:
print(f" {term}: {score:.4f}")
def load_data(directory):
files = dict()
for filename in os.listdir(directory):
with open(os.path.join(directory, filename)) as f:
contents = [
word.lower() for word in
nltk.word_tokenize(f.read())
if word.isalpha()
]
frequencies = dict()
for word in contents:
if word not in frequencies:
frequencies[word] = 1
else:
frequencies[word] += 1
files[filename] = frequencies
return files
if __name__ == "__main__":
main()
但是当我在Powershell中运行python.\main.py.\shelock\u holmes\时
我得到了这个令人困惑的错误:
Loading data...
Traceback (most recent call last):
File ".\main.py", line 65, in <module>
main()
File ".\main.py", line 22, in main
idfs[word] = idf
TypeError: list indices must be integers or slices, not str
正在加载数据。。。
回溯(最近一次呼叫最后一次):
文件“\main.py”,第65行,在
main()
文件“\main.py”,第22行,在main中
idfs[word]=idf
TypeError:列表索引必须是整数或片,而不是str
有人能帮我吗?您将
idf
定义为一个列表:
idfs = list()
如果udfs
是一个列表,则在此分配中:
idfs[word] = idf
word
必须是整数,因为它指定了列表中的索引或位置
但似乎单词
是str
的列表,因此在迭代中:
for word in words:
word
是一个str
。由于str
不是整数,因此该行
idfs[word] = idf
导致您得到的错误,原因正是它所解释的。也许idfs
应该是一个dict
而不是一个列表,定义如下:
idfs = dict()
然后,线路:
idfs[word] = idf
将
word
解释为字典中的键,并将idf
指定为dict
中该键的值。字典键可以是任何对象,通常是字符串,因此这很有意义。实际上idfs
是一个列表。idf[word]=idf像字典一样为其添加键值。因此,您应该将其设置为字典,而不是idfs=list()
idfs={}。否则,如果您需要列表,请使用.append()
将项目添加到末尾。事实上,错误消息有足够的信息,我不知道可以添加什么。它显示了一行代码,上面写着idfs[word]=idf
。这意味着您有一个名为idfs
的列表,并且希望使用word
作为索引。错误消息说有一个TypeError,意思是,一个与某个东西的类型有关的错误。然后它告诉您,您试图用作索引的对象(即,word
)是一个字符串(str
),而索引到列表中需要一个整数或一个片段。到底是什么让人困惑?仔细想想你想用这行代码解决什么问题。嘿!你知道,我12岁了!