Python
Write function words() that takes one input argument—a file name—and returns the list of actual words (without punctuation symbols !,.:;?) in the file.
>>> words('example.txt')
['The', '3', 'lines', 'in', 'this', 'file', 'end', 'with', 'the', 'new', 'line', 'character', 'There', 'is', 'a', 'blank', 'line', 'above', 'this', 'line']
import string def words(filename): words_in_file = [] try: f = open(filename) for line in f: cleaned_line = '' for ch in line.strip(): if ch not in string.punctuation: cleaned_line += ch line_words = cleaned_line.split() words_in_file += line_words f.close() except FileNotFoundError: print(filename + " is not found") return words_in_file print(words('example.txt'))
Get Answers For Free
Most questions answered within 1 hours.