1

For the purpose of learning Python, I'm trying to build an application which does the spell check of a file. I see that in its most basic usage the SpellChecker library validates words from an array of known/unknown words:

from spellchecker import SpellChecker

spell = SpellChecker()
spell['morning']  # True
'morning' in spell  # True

# find those words from a list of words that are found in the dictionary
spell.known(['morning', 'hapenning'])  # {'morning'}

# find those words from a list of words that are not found in the dictionary
spell.unknown(['morning', 'hapenning'])  # {'hapenning'}

Since I want to validate a whole file, I thought to add a function to read a text file and convert it into an array of words to be checked:

def readFile(fileName):
    fileObj = open(fileName, "r")  # opens the file in read mode
    words = fileObj.read().splitlines()  # puts the file into an array
    fileObj.close()
    return words

Unfortunately, the above function puts an entire line (and not the single words) into the array. I've tried with:

words = fileObj.read().splitlines().split() 

But split() can't be applied on the splitlines() function. Any idea how to achieve that ?

Carla
  • 3,064
  • 8
  • 36
  • 65

1 Answers1

3

You have to call split() on each separate line.

words = []
lines = fileObj.read().splitlines()
for line in lines:
    words.extend(line.split())
John Gordon
  • 29,573
  • 7
  • 33
  • 58