python - “类型错误 : list indices must be integers, 不是 str”Python 3

标签 python

我需要一些关于这项作业的帮助(第一次在 SE 上发帖,如果有的话请原谅我缺乏发帖礼仪)

因此,对于这段代码,我必须编写一个拼写检查器。基本上它应该做的是:

1.) 检查两个列表(一个是字典,我们在其中获取所有拼写正确的单词,另一个是用户输入列表,其中应该有一个或两个拼写错误的单词)

2.) 建议用正确的单词代替拼写错误的单词(例如,如果我拼写了 heloo,拼写检查器会说我拼写错误,并建议该单词是 hello、help 等)

我现在最大的问题是在第 19 行,我得到列表索引必须是整数问题。

感谢任何帮助,并且非常感谢帮助完成此任务!我觉得语法之外还有更多可以改进的地方。谢谢。

这是代码,尚未完全完成

import re

def words_from_file(filename):
try:
    f = open(filename, "r")
    words = re.split(r"[,.;:?\s]+", f.read())
    f.close()
    return [word for word in words if word]
except IOError:
    print("Error opening %s for reading. Quitting" % (filename))
    exit()


user_word = words_from_file('user_word.txt')
suggestion = words_from_file('big_word_list.txt')
sug_list = []

for a in user_word:
    if user_word[a] not in suggestion:
        print ("Spelling error: %s"%(user_word[a]))
        for i in suggestion:
            for j in suggestion[i]:
                if len(suggestion[i][j]) == len(user_word[a]-2):
                    count = 0
                    similarities = len(user_word[a])
                    for k in suggestion[i][j]:
                        if suggestion[i][j][k] in suggestion:
                            count+=1
                            if count >= similarities:
                                sug_list.append(suggestion[i][j])

最佳答案

更改:

for a in user_word:
    if user_word[a] not in suggestion:

进入:

for a in user_word:
    if a not in suggestion:

因为 user_word 列表中的所有项目都将使用 a 变量进行迭代。 a 将在每次迭代中包含从行分割中获得的非空字符串。您只能将数字索引与列表类型一起使用。最初,您使用字符串代替数字索引,这会导致错误消息。

关于python - “类型错误 : list indices must be integers, 不是 str”Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29548548/

相关文章:

python - 在 python 3 中“尝试” 'duration'

Python 通过 ssh 终止进程

python - 为随机变量分配随机值

php - 如何使用 urllib 对 url 进行编码

python - Django 管理 "save and view on site"按钮

python - 如何加快DataFrame设置速度?

python - 默认检查同一个表的列

python - 使用 Python 创建图表和图形

Python unicode 字符串到字符串?

python - 如何解决 Azure 文本分析的导入错误