This is the "Clean up the words" challenge from CodeEval:
Challenge
Given a list of words mixed with extra symbols. Write a program that will clean up the words from extra numbers and symbols.
Specifications
- The first argument is a path to a file.
- Each line includes a test case.
- Each test case is a list of words.
- Letters are both lowercase and uppercase, and mixed with extra symbols.
- Print the words separated by spaces in lowercase letters.
Constraints
- The length of a test case together with extra symbols can be in a range from 10 to 100 symbols.
- The number of test cases is 40.
Input Sample
(--9Hello----World...--) Can 0$9 ---you~ 13What213are;11you-123+138doing7
Output Sample
hello world can you what are you doing
In a previous question someone joked the program would be much shorter / simpler in Python. I accepted this as a challenge and excuse to practice Python.
Solution:
import sys
import re
def sanitized(line):
sanitized_line = re.sub("[^a-zA-Z]+", " ", line)
return sanitized_line.lower().strip()
def main(file):
with open(file, 'r') as input_file:
for line in input_file:
print(sanitized(line))
if __name__ == "__main__":
try:
file = sys.argv[1]
main(file)
except:
print("No argument provided.")
It's so succinct I'm unsure there's enough for a review, but this site surprised me in the past.
re.sub(r'\W+', '', line)
. Apparently I was about to suggest''.join(ch for ch in string.printable if ch.isalnum())
but in this case using a regex is far better when talking to the speed of processing. \$\endgroup\$W
regex shortcut won't apply since this also removes numbers. For the same reasonisalpha
is preferable overisalnum
\$\endgroup\$re.compile
before actuallysub
ing. IT saves a fewusec
s. Have a quick look here \$\endgroup\$