-2

I am going to paste my entire code so that you can understand everything you need to know, even though I understand that you probably don't need it all. I am also going to warn you that I am very new to programming so I am probably very inefficient with my code and very messy and I apologize for that! If you see anything else I need to fix I would appreciate it.

Summary of program goal: Read a file for a 3-letter word, ask me if the word is a 3-letter word for verification before inserting it into a text document with a list of its (known) 3-letter words. (In order to do that it needs to define each character of the 3-letter word found.(?))

# wdf - word functions
import sys
import time
import re
import copy
import string
from string import ascii_lowercase
from random import *


def is_three_letters(word): # code from ChristianFigueroa @ stackoverflow.com
    return bool(re.match(r"[a-zA-Z/d]{3}$", word))


def i_otpt():
    f = open("output.txt", "a")
    f.write("\n")
    f.write("\n")
    f.write(">-------------------------------<")
    f.write("\n")
    f.write("\n")
    f.write(time.asctime(time.localtime(time.time())))
    f.write("\n")
    f.write("----N-E-W--O-U-T-P-U-T--L-O-G----")
    f.write("\n")
    f.write("\n")
    f.close()


def o_otpt():
    f = open("output.txt", "a")
    f.write("\n")
    f.write("----E-N-D--O-U-T-P-U-T--L-O-G----")
    f.close()


def otpt(tx):
    f = open("output.txt", "a")
    f.write(str(tx))
    f.write("\n")
    f.close()


def otpt2(tx, tx2):
    f = open("output.txt", "a")
    f.write(str(tx))
    f.write(" ")
    f.write(str(tx2))
    f.write("\n")
    f.close()


def otpt3(tx, tx2, tx3):
    file = open("output.txt", "a")
    file.write(str(tx))
    file.write(" ")
    file.write(str(tx2))
    file.write(" ")
    file.write(str(tx3))
    file.write("\n")
    file.close()


def wd_sc_3(name_of_file):
    with open(name_of_file + ".txt") as f:
        lines = f.readlines()
        wdl = []
        x = 0
        for line in lines:
            words = [word for word in line.split() if len(word) == 3 and all(ch in ascii_lowercase for ch in word)]
            x += 1
            if x % 2 == 1:
                wdl.append(words)
            l = 0
            lx = wdl[l][0]
            dvd = dict(enumerate(lx, 1))
            l1 = dvd[0]
            l2 = dvd[1]
            l3 = dvd[2]
            word3(l1, l2, l3)
            l += 1
        f.close()
        v = len(wdl)
        print("Found ", v, " words")
        n = 0
        file = open("read3.txt", "a")
        file.write("\n")
        while True:
            file.write((wdl[n][0]))
            file.write("\n")
            n += 1
            if n >= v:
                break


def word3(a, b, c):  # Defines a 3 letter word and prints it as one word
    wd3 = (a + b + c)
    i_otpt()
    sys.stdout.write("Word check: ")
    otpt2("Word check: ", wd3)
    for var in a:
        sys.stdout.write(var)
        sys.stdout.flush()
    for var in b:
        sys.stdout.write(var)
        sys.stdout.flush()
    for var in c:
        sys.stdout.write(var)
        sys.stdout.flush()
        sys.stdout.write("\n")
    sd1 = 0
    slx = 0
    file = open("list_of_words_3.txt", "r")
    otpt("\nWord 3 file opened to read.")
    while slx <= 250:
        file.readline(slx)
        for line in file:
            otpt2(" -Reading line", (int(slx) + 1))
            if wd3 in line:
                sd1 = 1
                file.close()
                print("(-)Word already stored", "\n")
                otpt("Word already stored")
                otpt("Word 3 file closed.")
                break
            elif not line.strip():
                otpt("   -Empty")
                continue
            elif wd3 not in line:
                slx += 1
                continue
            elif slx == 250:
                file.close()
                otpt("Word 3 file full")
                otpt("Word 3 file closed.")
                break
            else:
                print("Something went wrong.")
                otpt("Something went wrong. (1)")
                break
        slx = 251
        break
    file.close()
    otpt("Word 3 file closed.")
    if slx == 251:
        file = open("list_of_words_3.txt", "a")
        otpt("Word 3 file opened to add word.")
        if sd1 == 0:
            print("Is ", wd3, " a word?")
            ans = input("---> ")
            if ans == "yes":
                file.write(wd3)
                otpt3("Word ", wd3, " added to file.")
                file.write(",\n")
                otpt("Word 3 file closed.")
                file.close()
                sys.stdout.write("(+)New word added: ")
                sys.stdout.write(wd3)
                sys.stdout.write("!")
                otpt3("New word added: ", wd3, "!")
                file.close()
            if ans == "no":
                print("Okay, registering ", wd3, " as not a word")
                file.close()
                otpt("Opening not a word 3 file")
                file = open("list_of_not_words_3.txt", "r")
                sly = 0
                sd2 = 0
                while sly <= 250:
                    file.readline(sly)
                    for line in file:
                        otpt2(" -Reading line", (int(sly) + 1))
                        if wd3 in line:
                            sd2 = 1
                            file.close()
                            otpt("Word already stored")
                            otpt("Not a word 3 file closed.")
                            break
                        elif not line.strip():
                            otpt("   -Empty")
                            continue
                        elif wd3 not in line:
                            sly += 1
                            continue
                        elif sly == 250:
                            file.close()
                            otpt("Not a 3 word file full")
                            otpt("Not a 3 word file closed.")
                            break
                        else:
                            print("Something went wrong.")
                            otpt("Something went wrong. (2)")
                            break
                    sly = 251
                    break
                file.close()
                otpt("Not a 3 word file closed.")
                if sly == 251:
                    file = open("list_of_not_words_3.txt", "a")
                    otpt("Not a 3 word file opened to add word.")
                    if sd2 == 0:
                        if ans == "yes":
                            file.write(wd3)
                            otpt3("Word ", wd3, " added to file.")
                            file.write(",\n")
                            otpt("Not a word 3 file closed.")
                            file.close()
                            otpt3("New word added: ", wd3, "!")
                            file.close()
                    if sd2 == 1:
                        otpt("No need to add word")
                else:
                    otpt("No word added")
        if sd1 == 1:
            otpt("No need to add word")
    else:
        print("No word added.")
        otpt("No word added")


wd_sc_3("test")

Error:

Traceback (most recent call last):
Found  65  words
  File "/Users/ethanmcrae/PycharmProjects/AI/wdf.py", line 222, in <module>
    wd_sc_3("test")
  File "/Users/ethanmcrae/PycharmProjects/AI/wdf.py", line 90, in wd_sc_3
    file.write((wdl[n][0]))
IndexError: list index out of range

Process finished with exit code 1

I realize this problem will probably consume a decent amount of time to fix, so I understand if this takes some time to get resolved.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Ethan McRae
  • 124
  • 2
  • 13
  • 1
    Possible duplicate of [IndexError: list index out of range and python](https://stackoverflow.com/questions/1098643/indexerror-list-index-out-of-range-and-python) – l'L'l Aug 15 '17 at 23:13
  • [Catch the error](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) and in the except suite, inspect `wdl` - maybe by printing it or a portion of it. ... Or maybe `n` is the problem - how *big* is `wdl`? What are its *dimensions*. – wwii Aug 15 '17 at 23:14
  • 1
    It's hard to tell with a large quantity of code and no input file example. Did you try printing out the variable before trying to access the nth or 0th index of it? It may not be what you expect. – Paul Rooney Aug 15 '17 at 23:15
  • Also try running the code with an empty input. Your code presumes that there will be at least one item in the list `wdl` after the lines from the file are processed. Perhaps `for x in wdl:` will make a more appropriate loop than `while True:` (line 88). – Paul Rooney Aug 15 '17 at 23:26
  • Please do **not dump your code like this**. StackOverflow is *not a debugging service*, or a *code review service*. It is a question-and-answer site, and you are suppose to create a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve). – juanpa.arrivillaga Aug 15 '17 at 23:28
  • Also, why in the name of everything that is holy are you using `sys.stdout.write`? **use `print`** and string formatting. It will make your code much, much cleaner. There are very few instances where using `sys.stdout` directly is warrented. – juanpa.arrivillaga Aug 15 '17 at 23:30
  • @l'L'l I read through all the answers of that post and none of them helped me. – Ethan McRae Aug 16 '17 at 00:12
  • @juanpa.arrivillaga Thanks for informing me of that. I posted the entire code so people could run it if they wanted to help them find the error, but I will fix my post and maybe put a link to a pastebin or something if someone wants to look further into it. – Ethan McRae Aug 16 '17 at 00:14

1 Answers1

1

found your issue in this section of your code (towards the middle)

for line in lines:
    words = [word for word in line.split() if len(word) == 3 and all(ch in ascii_lowercase for ch in word)]
    x += 1
    if x % 2 == 1:
        wdl.append(words)
    l = 0
    lx = wdl[l][0]
    dvd = dict(enumerate(lx, 1))
    l1 = dvd[0]
    l2 = dvd[1]
    l3 = dvd[2]
    word3(l1, l2, l3)
    l += 1

in the for loop you keep setting L to 0 so only wdl[0][n] is set it never goes to wdl[1][n]

Karan Shishoo
  • 2,402
  • 2
  • 17
  • 32