Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python Does anyone know why this happens?

Average_Student

New Coder
in my computer science class we are learnign about searching through files.

I have a binary and linear searching method where they search the same document for spelling errors by comparing it to a dicitonary.
the problem is that if I try to run them back to back it wont work. they both work seperately but not one after another. I suspect it is because the file itself remembers what position you searched last because if you close and then re-open the file between function calls, it works.

her is my code if you would like to see:


Python:
import re
 
# This function takes in a line of text and returns
# a list of words in the line.
# basically just to make the formatting of the dictionary and alice in wonderland match
# also splits into lines which allow us to detect which line a word is on
def split_line(line):
    return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?',line)




# Opens the dictionary file and stores it in the variable 'file'
file = open("dictionary.txt")


dictionary_list = []
for line in file:
    # Strips the dictionary for formatting reasons
    line = line.strip()
    # Appends dicitionary to a list
    dictionary_list.append(line)
 
file.close()

# Opens the alice in wonderland file
file = open("alice_in_wonderland_200.txt")


# Function that uses the linear search method to find the spelling errors
def linear_search():
    print('- - - Linear Search - - -')
    #counter do detect what line a word is on
    line_number = 0
    # for each line in the file
    for line in file:
        # Variable we use to tell what line the spelling error is on
        line_number += 1
        # splits the lines for formatting reasons and sets it to 'words'
        for words in split_line(line):
            i = 0
            # a loop that continue until the dictionart is over or it find a spelling error
            while i < len(dictionary_list) and dictionary_list != words.upper():
                i += 1
            if not i < len(dictionary_list):
                print('line', line_number, 'has a possible misspelled word:', words)


# A binary search function that compares the words uning < > symbols to find the spelling errors faster
def binary_search():
    print('- - - Binary Search - - -')
    line_number = 0
    # for each line in the file
    for line in file:
        line_number += 1
        # splits the lines for formatting reasons and sets it to 'words'
        for words in split_line(line):
            # a key to tell the program what word its looking for
            key = words.upper()
            lower_bound = 0
            upper_bound = len(dictionary_list)-1
            found = False
            # Loop until we find the item, or our upper/lower bounds meet
            while lower_bound <= upper_bound and not found:
            
                # Find the middle position
                middle_pos = (lower_bound + upper_bound) // 2
            
                # Figure out if we:
                # move up the lower bound, or
                # move down the upper bound, or
                # we found what we are looking for
                if dictionary_list[middle_pos] < key:
                    lower_bound = middle_pos + 1
                elif dictionary_list[middle_pos] > key:
                    upper_bound = middle_pos - 1
                    
                else:
                    found = True
                    
                    
            # if it doesent find the word, aka its a spelling mistake, it prints this
            if not found:
                print('line',line_number,'has a possible misspelled word:', words)
            



# just calls the functions
linear_search()
print('\n')
# here I close and open the files because the second function wont work if I dont
file.close
file = open('alice_in_wonderland_200.txt')
binary_search()
 
I suspect it is because the file itself remembers what position you searched last because if you close and then re-open the file between function calls, it works.
Yes, that surely is your problem. After your first search you are at end-of-file, and the second search falls right through without being able to read anything. Indeed, reopening the file does the trick. If you don't like that, perhaps Python has a command (like the seek() command in C) to set the file position back to zero.
 
Just a suggestion, I find it is easier to use an implicit context manager. That way you never have to worry about closing a file. For example:

Code:
for line in open('dictionary.txt'):
    dictionary_list.append(line.strip())

The file is automatically closed when the loop terminates.

Also, when you comment a function, put the comment inside as in

Code:
def split_line(line):
    """
    This function takes in a line of text and returns a list of words in the line.
    """
    return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?',line)
 
However if you want to do multiple searches in one file I would choose to leave it open and use file.seek(0) before each search.
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom