import re def is_float(text): '''Return whether the given string represents a float.''' return re.search(r'^-?\d+(\.\d+)?$', text) != None def extract_names(text): '''Returns the first and last names of a full name as a 2-tuple''' match = re.search(r'^\s*([A-Z]\w*)\s+([A-Z]\w*)\s*$', text) if match != None: # yes, this is a match return (match.group(1), match.group(2) ) else: print('This isn\'t a valid full name') return None def find_long_words(filename, num_chars): '''Print all words in filename that are at least num_chars characters long.''' input_file = open(filename) text = input_file.read().lower() input_file.close() regex = r'\b[a-zA-Z]{' + str(num_chars) + r',}\b' words = re.findall(regex, text) for word in set(words): print(word) def print_comments(filename): '''Print all the non-docstring comments in the Python program stored in filename.''' input_file = open(filename) for line in input_file: # loop over the lines of file line = line.strip() match = re.search(r'#([^\']*)$', line) # simple version # match = re.search(r'#(.*)$', line) if match != None: # yes, this line has ' a comment print(match.group(1)) input_file.close()