0

I am building a custom "translator" for abbreviations. It is supposed to take a string input, split it into the individual words and return each word as an abbreviation.

Example: Input: above and aloft Returns: abv & alft

The abbreviations are retrieved from a txt file where the abbreviation and the key phrase are separated by a tab. Every pair on the separate line.

    import csv

# Used to lowercase the library
file = open('lib.txt', 'r')

lines = [line.lower() for line in file]
with open('lib.txt', 'w') as out:
     out.writelines(sorted(lines))

# Get user input
eng = input("Plain english input:")

# Split input into separate words
words = eng.split()

# Search every word in the file, return the first word (abbreviation) in the respective line
with open('lib.txt', newline='') as lib:
    lib_reader = csv.reader(lib, delimiter='\t')
    lib.seek(0)
    print(words)
    for x in words:
        print('1')
        lib.seek(0)
        for lib in lib_reader:
            print('2')
            if x in lib:
                print(lib[0])
                break


For whatever reason, it runs great, finds the first word, breaks, comes back to the first loop and gives an error on the lib.seek(0).

AttributeError: 'list' object has no attribute 'seek'

From what I understand, it has to reset the cursor to the beginning of the text in the file in order to start the search over for the second word. seek() is there to prevent it from exiting the loop and continue searching for the next parameter.

  • 1
    `for lib in lib_reader:` is an assignment to the variable `lib`, overwriting its previous value as the open file object. – jasonharper Jul 22 '21 at 03:50
  • it would be simpler (and should run faster) if you would read all data from `lib.txt` to memory. – furas Jul 22 '21 at 07:45

1 Answers1

1

I think maybe you are using the same variable for two things. That collision replaces lib the file handle with lib the row from the csv reader which is a list. That is why you receive that error, because the list does not have a seek method.

Try using lib_row instead of lib for each row read from lib_reader.

Python doesn't have block scoping so the variables in for loops are the same as the variables in the function.

        for lib_row in lib_reader:
            print('2')
            if x in lib_row:
                print(lib_row[0])
                break
Ian Wilson
  • 6,223
  • 1
  • 16
  • 24