jude
jude

Reputation: 11

How to get python to count words and skip a variable

I'm trying to get python to count unique words and skip over the variable JUMBO and then store it in a dictionary.

book_string = 'you cant can do it it it'
JUMBO = 'cant'
book_string = book_string.split(' ')

word_count = {}
for w in book_string:
    if w == JUMBO:
        continue
    if w != '':
        word_count[w] = 0
for w in book_string:
    if w != '':
        word_count[w] += 1
print(word_count)
# output: {'you': 1, 'cant': 1, 'can': 1, 'do': 1, 'it': 3}

Upvotes: 0

Views: 64

Answers (4)

hpchavaz
hpchavaz

Reputation: 1388

You should follow Thonnu answer, and use `collections.Counter.

Any way without importing the library, it can also be short (but presumably slower when the number of words is large), by taking use of :

  • split default behavior
  • dict.get optional argument value for missing keys:
book_string = 'you cant can do it it it  '
JUMBO = 'cant'

word_count = {}
for w in book_string.split(' '):
    word_count[w] = word_count.get(w,0) + 1

word_count.pop(JUMBO)

print(word_count)

Note that you cannot replace the init / for loop by a dict comprehension as the dict must be defined before being used :

word_count = {w:word_count.get(w,0)+1 for w in book_string.split(' ')}

>>>
NameError: name 'word_count' is not defined

Upvotes: 0

Arash
Arash

Reputation: 607

Just another solution without Counter.

book_string, JUMBO = "you cant can do it it it", "cant"
filtered_book_string_list = list(filter(lambda x: x != JUMBO, book_string.split()))
print({i: filtered_book_string_list.count(i) for i in filtered_book_string_list})

Upvotes: 0

Nesi
Nesi

Reputation: 438

If you want to do it without importing a library. You can do it like this.

book_string = 'you cant can do it it it  '
JUMBO = 'cant'
book_string = book_string.split(' ')

word_count = {}

for w in book_string:
    if w == JUMBO or w == '':  # skip JUMBO and ''
        continue
    elif w not in word_count:  # if not in dictionary, create.
        word_count[w] = 1
    elif w in word_count:  # if found in dict increase count.
        word_count[w] += 1

print(word_count)

Upvotes: 0

The Thonnu
The Thonnu

Reputation: 3624

from collections import Counter
book_string = 'you cant can do it it it'
JUMBO = 'cant'
count = dict(Counter(book_string.split()))
count.pop(JUMBO)
print(count)

Output:

{'you': 1, 'can': 1, 'do': 1, 'it': 3}

Upvotes: 2

Related Questions