-1

我正在编写一个程序来查看一个单词中是否包含三个连续的双字母,例如簿记。

当我尝试运行程序时,我收到错误,TypeError: 'int' object is ubsubscriptable。有什么理由吗?

def find_word(string):

    count = 0
    for eachLetter in range(len(string)):
        if eachLetter[count] == eachLetter[count + 1] and eachLetter[count+ 2] == eachLetter[count + 3] and eachLetter[count+ 4] == eachLetter[count + 5]:
            print string
        else:
            count = count + 1


def main():

  try:
  fin = open('words.txt') #open the file
  except:
  print("No file")

  for eachLine in fin:
 string = eachLine
 find_word(string)


if __name__== '__main__':
  main()
4

3 回答 3

3

你的循环:

for eachLetter in range(len(string)):

将小于字符串长度的 0 到 1 的数字赋给变量eachLetter;在此之后,eachLetter[count]没有任何意义。

你的意思是string[eachLetter],等等?

请注意,您还会遇到索引错误;例如,当您到达“bookkeeping”的第 8 个字母时,没有要检查的字符 8+5 = 13,您的程序就会崩溃。

由于这似乎是家庭作业,我将把它作为练习留给你,让你弄清楚如何尽快停止循环 5 个字符。

于 2013-02-19T12:22:50.873 回答
1

Here's your error:

if eachLetter[count]

Here eachLetter is int, because range returns list of ints.

于 2013-02-19T12:24:09.110 回答
0
fin = open('words.txt')
string = fin.readline()

def find_word(string):
    for string in fin:
        count = 0
        for count in range(len(string)-5):
              if string[count] == string[count + 1] and string[count+ 2] == string[count + 3] and string[count+ 4] == string[count + 5]:
                 print(string)





def main(fin):

    for string in fin:

        return find_word(string)


main(fin)
于 2017-11-16T08:54:21.117 回答