In today’s exercise, we have two snippets of code that produce the same output. They both count words. However, their code style is different.
What is the best code snippet between the two and why? Drop your comment in the comments section and click the explanation button to see what code is better.
Code Snippet 1
def word_count(text):
count = {}
for word in text.lower().strip().replace('.', '').replace(',', '').replace('!', '').replace('?', '').split():
if word in count:
count[word] += 1
else:
count[word] = 1
return count
text = "This is a sample text with several words. This is a test."
result = word_count(text)
print(result)
Code Snippet 2
def word_count(text):
text = text.lower().strip()
text = text.replace('.', '').replace(',', '').replace('!', '').replace('?', '')
words = text.split()
count = {}
for word in words:
if word in count:
count[word] += 1
else:
count[word] = 1
return count
if __name__ == "__main__":
text = "This is a sample text with several words. This is a test."
result = word_count(text)
print(result)
Snippet 2 is better. Because the code readability, maintainability, Python best practice of including the 'if __name__ == "__main__"' block.