Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions exercises/practice/word-count/.approaches/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"introduction": {
"authors": ["bethanyg"],
"contributors": ["yrahcaz7"]
},
"approaches": [
{
"uuid": "a3dd190d-ff92-4190-b8aa-2b4b46171b46",
"slug": "str-iteration-with-dict",
"title": "String Iteration with Dictionary",
"blurb": "Iterate over the sentence to filter out punctuation and sum word counts with a dict.",
"authors": ["bethanyg"]
},
{
"uuid": "5a5f4f89-b016-48ed-9316-a49cadf9735f",
"slug": "str-replace-with-dict",
"title": "String Replace with Mutable Dictionary",
"blurb": "Use str.replace and str.strip to filter out punctuation and sum word counts with a dict.",
"authors": ["bethanyg"],
"contributors": ["yrahcaz7"]
},
{
"uuid": "3d5d629f-58b6-43c5-9470-30b30b193892",
"slug": "str-replace-with-comprehensions",
"title": "String Replace with Comprehensions",
"blurb": "Use str.replace and str.strip to filter out punctuation and sum word counts with comprehensions.",
"authors": ["bethanyg"],
"contributors": ["yrahcaz7"]
},
{
"uuid": "373182b1-8d21-4ee6-aa49-94ff6a9c57a1",
"slug": "str-replace-with-collections",
"title": "String Replace with Collections",
"blurb": "Use str.replace and str.strip to filter out punctuation and let collections.Counter do the rest.",
"authors": ["bethanyg"],
"contributors": ["yrahcaz7"]
},
{
"uuid": "2afed504-500d-4415-a507-b78311bde777",
"slug": "using-the-re-module",
"title": "Using the re Module",
"blurb": "Python's re module is both versatile and powerful.",
"authors": ["bethanyg"],
"contributors": ["yrahcaz7"]
},
{
"uuid": "0aa44eec-1c71-4937-8e3f-c45cbba22cc1",
"slug": "str-translate-with-counter",
"title": "String Translate with Counter",
"blurb": "Use str.translate to filter out punctuation and then tally words with collections.Counter.",
"authors": ["bethanyg"],
"contributors": ["yrahcaz7"]
},
{
"uuid": "182463b2-fcfa-4445-967c-8b185b7853c9",
"slug": "filter-with-counter",
"title": "Filter with Counter",
"blurb": "Use the built-in filter function to clean the sentence and collections.Counter to count the words.",
"authors": ["bethanyg", "yrahcaz7"]
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# `filter()` with `collections.Counter()`

```python
from collections import Counter
from string import punctuation

def count_words(sentence):
words = filter(None, (
Comment thread
Yrahcaz7 marked this conversation as resolved.
Resolved
word.strip(punctuation)
for word in sentence
.lower()
.replace("_", " ")
.replace(",", " ")
.split()
))
return Counter(words)
```

This approach begins by lowercasing the input sentence with [`str.lower()`][str-lower] and cleaning the input using [`str.replace()`][str-replace].
It then splits the sentence into words and iterates over them using [`str.split()`][str-split] and a [generator expression][generator-expression].

For each word in the sentence, any leftover punctuation is removed using [`str.strip()`][str-strip] and [`string.punctuation`][string-punctuation].
(Importing `punctuation` is only for convenience, a string containing ``!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`` would work as well, as long as the input only contains ASCII characters.)

Since the punctuation removal may leave empty strings, the generator expression is fed into [`filter()`][builtin-filter] with `None` as the first argument, which makes `filter()` discard any items that evaluate to `False` (i.e., items that are "falsy").
An alternative would be to provide the [lambda][lambda] expression `lambda item: item` as the first argument instead of `None`, which would yield the same results.

Once the words are `filter`ed, a [`Counter`][collections-counter] from the [`collections` module][collections-module] is constructed from the resulting iterator. Since `Counter`s are a subclass of dictionaries, the `Counter` can then be directly returned as the result.

## Variation 1

Alternatively, an `if` clause could be used instead of `filter()`, and the result can be directly fed into `Counter()`:

```python
from collections import Counter
from string import punctuation

def count_words(sentence):
return Counter(
word.strip(punctuation)
for word in sentence
.lower()
.replace("_", " ")
.replace(",", " ")
.split()
if word.strip(punctuation)
)
```

However, this has extra overhead from calling `strip()` twice and is debatably less readable.


[builtin-filter]: https://docs.python.org/3/builtins/functions.html#filter
[collections-counter]: https://docs.python.org/3/library/collections.html#collections.Counter
[collections-module]: https://docs.python.org/3/library/collections.html
[generator-expression]: https://dbader.org/blog/python-generator-expressions
[lambda]: https://docs.python.org/3/glossary.html#term-lambda
[string-punctuation]: https://docs.python.org/3/library/string.html#string.punctuation
[str-lower]: https://docs.python.org/3/builtins/stdtypes.html#str.lower
[str-replace]: https://docs.python.org/3/builtins/stdtypes.html#str.replace
[str-split]: https://docs.python.org/3/builtins/stdtypes.html#str.split
[str-strip]: https://docs.python.org/3/builtins/stdtypes.html#str.strip
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
def count_words(sentence):
words = filter(None, (
word.strip(string.punctuation)
for word in sentence.lower().replace("_", " ").replace(",", " ").split()
))
return Counter(words)
Loading
Loading