Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Word search in grid
#1
Supposed to ask the user to input the file name, then read and append each line from the file to a list and display the grid. Then find some words in the puzzle grid. Actual assignment was to ask the user to supply the name of the file which contains the words to be found, but didn't even bother with that cause the rest was complicated enough.

import io
import array
import re

solutions = ['java', 'ethernet', 'stock', 'active', 'act', 'cot', 'net', 'nut', 'caps', 'lap', 'notinthegrid']

def gettingfile():
    try:
        global files
        files = input('Enter the file name: ')
        with open (files + '.txt',) as opened:
            opened.readlines()
            opened.close()
            pass
    except IOError:
        print('Invalid file name. Try again.')
        gettingfile()

    with open(files + '.txt') as o:
        for x in o.readlines():
            temp = x.strip()
            print(temp)

gettingfile()
wordlist=[]
with open(files + '.txt', 'r') as line:
    for line in line:
        wordlist.append(line.split())
        
with open(files + '.txt', 'a') as derp:
    for derp in wordlist:
        derp.write(wordlist.strip('\n'))
    
length = wordlist.index('\n')+1

characters = [(letter, divmod(index, length))
            for  index, letter in enumerate (wordlist)]

wordlines = {}
directions = {'going downwards':0, 'going downwards and left diagonally':-1, 'going downwards and right diagonally':1}

for word_direction, directions in directions.items():
    wordlines[word_direction] = []
    for x in range(length):
        for i in range(x, len(characters), length + directions):
            wordlines[word_direction].append(characters[i])
        wordlines[word_direction].append('\n')

wordlines['going right'] = characters
wordlines['going left'] = [i for i in reversed(characters)]
wordlines['going upwards'] = [i for i in reversed(wordlines['going downwards'])]
wordlines['going upwards and left diagonally'] = [i for i in reversed(wordlines['going downwards and right diagonally'])]
wordlines['going upwards and right diagonally'] = [i for i in reversed(wordlines['going downwards and left diagonally'])]


def printitout(direction, tuple, lines):
    print ("Keep in mind, rows are horizontal and columns are vertical.\n")
    for direction, tuple in lines.items():
        string = ''.join([i[0] for i in tuple])
        for word in solutions:
            if word in string:
                coordinates = tuple[string.index(word)][1]
                print (word, 'is at row', coordinates[0]+1, 'and column', coordinates[1]+1, direction + ".")

printitout(word_direction, tuple, wordlines)
Error:
Error:
derp.write(wordlist.strip('\n')) AttributeError: 'list' object has no attribute 'write'
Initially the code didn't include the part that gives error. I was getting another error and was advised to strip the line/list? Confused. So I typed that. But initial code was:

import io
import array
import re

solutions = ['java', 'ethernet', 'stock', 'active', 'act', 'cot', 'net', 'nut', 'caps', 'lap', 'notinthegrid']

def gettingfile():
    try:
        global files
        files = input('Enter the file name: ')
        with open (files + '.txt',) as opened:
            opened.readlines()
            opened.close()
            pass
    except IOError:
        print('Invalid file name. Try again.')
        gettingfile()

    with open(files + '.txt') as o:
        for x in o.readlines():
            temp = x.strip()
            print(temp)

gettingfile()
wordlist=[]
with open(files + '.txt', 'r') as line:
    for line in line:
        wordlist.append(line.split())
    
length = wordlist.index('\n')+1

characters = [(letter, divmod(index, length))
            for  index, letter in enumerate (wordlist)]

wordlines = {}
directions = {'going downwards':0, 'going downwards and left diagonally':-1, 'going downwards and right diagonally':1}

for word_direction, directions in directions.items():
    wordlines[word_direction] = []
    for x in range(length):
        for i in range(x, len(characters), length + directions):
            wordlines[word_direction].append(characters[i])
        wordlines[word_direction].append('\n')

wordlines['going right'] = characters
wordlines['going left'] = [i for i in reversed(characters)]
wordlines['going upwards'] = [i for i in reversed(wordlines['going downwards'])]
wordlines['going upwards and left diagonally'] = [i for i in reversed(wordlines['going downwards and right diagonally'])]
wordlines['going upwards and right diagonally'] = [i for i in reversed(wordlines['going downwards and left diagonally'])]


def printitout(direction, tuple, lines):
    print ("Keep in mind, rows are horizontal and columns are vertical.\n")
    for direction, tuple in lines.items():
        string = ''.join([i[0] for i in tuple])
        for word in solutions:
            if word in string:
                coordinates = tuple[string.index(word)][1]
                print (word, 'is at row', coordinates[0]+1, 'and column', coordinates[1]+1, direction + ".")

printitout(word_direction, tuple, wordlines)
Which gave this error:
Error:
length = wordlist.index('\n')+1 ValueError: '\n' is not in list
Reply
#2
What did you try to achieve with the statement length = wordlist.index('\n')+1?
Reply
#3
2nd code, line 29: Could add print(wordlist)
I think there is no '\n'
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply
#4
I think it's meant to get the length of the grid? I didn't actually write any of this code, I just found it online/got help from others. Someone helped me with the first part, to do with opening the file. All up to the length line that gives the error. Everything from that point onward is from another site. It was code written for finding words in a grid that was already input in the code, not imported from a file. So I was trying to merge the two together. But this happens.

Sorry I should have added the full output up to the error.

Output:
Enter the file name: grid xmfycxvtljlqbbybkoumjqwbt caubmeknbeydqmcnzyjpvrank aqactivexnyvwdvcoshoyaohg paghzkctudptjdphsztprhttl sbsnakjwqbouftmgnjqbtlinu tsewohvobdsduqjiffkyylodo oukwwefroyamapmlrrpvdolop cqkfxtlksjvtmtrsbycmqrrri kfervlqidqaxaoanfqjlmcpjh yoyywrbpfcjlfbcbbcoecspwl twbxetyuyufvvmauawjmbwlqh txokdexmdbtgvhpsvsqtmljdx dcatenrehteoxqdgeueljtrrn jarteqvtxejfsqddkbuhcysfq hpdrowssapxtrxhpdxcdhicon Traceback (most recent call last): File "D:\Uni\Essex\Lectures\CE151-4-AU-CO Introduction to Programming\Assignment 2\ex2.py", line 36, in <module> length = wordlist.index('\n')+1 ValueError: '\n' is not in list
If I type print(wordlist) it shows:

Output:
[['xmfycxvtljlqbbybkoumjqwbt'], ['caubmeknbeydqmcnzyjpvrank'], ['aqactivexnyvwdvcoshoyaohg'], ['paghzkctudptjdphsztprhttl'], ['sbsnakjwqbouftmgnjqbtlinu'], ['tsewohvobdsduqjiffkyylodo'], ['oukwwefroyamapmlrrpvdolop'], ['cqkfxtlksjvtmtrsbycmqrrri'], ['kfervlqidqaxaoanfqjlmcpjh'], ['yoyywrbpfcjlfbcbbcoecspwl'], ['twbxetyuyufvvmauawjmbwlqh'], ['txokdexmdbtgvhpsvsqtmljdx'], ['dcatenrehteoxqdgeueljtrrn'], ['jarteqvtxejfsqddkbuhcysfq'], ['hpdrowssapxtrxhpdxcdhicon']]
Reply
#5
When you use line.split() you removed the text file newline (\n). Thus there is no '\n' inside the wordlist.
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply
#6
Then how am I supposed to merge the two? End result should be a word search.
Reply
#7
Your main problem is that you try merging two programs which contain statements and logic that you don't understand... and you ask us to fix the issue for you. This is not how the "Homework" forum works, in my opinion.
Reply
#8
First, using global is bad practice and is not save. Pass the file name as a parameter to the function.

files = input('Enter the file name: ')

def gettingfile (files):
    with open(files, 'r') as opened:
        lines = opened. readlines () # you don't store the lines anywhere
        # there is no need to close the file manually with the close() method. The context manage ( the with statement ) is doing that for you automatically.
There is no need to call readlines method when you want to loop over the file.

for line in file_obj:
    print(line)
I can't understand what are you trying to achieve.
Just to find a bunch of words? Counting the rows of the file is it a part of the assignment?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
@squenson Ok, didn't know it didn't belong here. I thought it was an easy merge and was curious if it did work eventually. No worries. Hopefully I'll learn how the assignment actually works in 2 weeks once I recap whole module before exam x.x
Reply
#10
I think you misunderstood what squenson was saying.

It is a bad idea to take other people code and use them if you do not understand what the code does. You are better off starting again and writing yourself. You would have a better understanding of what your code doing, rather than just random stab to see if it works or not.

I don't know about the other guys. But I had a really hard time understand the logic of your code.
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020