0

I'm having a problem:

I mention:

I want to present the count number of each word in the following input that contains the following text:

"This is one number and is a good number"

The output that I would like to have, with the word count found inside the file.txt should be the following:

{'This': 1, 'is': 2, one': 1, 'number': 2, 'and': 1, 'a': 1, 'good': 1}

How can I put a "sorted" to sort the situation, instead of staying in descending order?

Someone can help me?

Thanks for listening!

fpb_i
  • 19
  • 3

1 Answers1

0

In newer Python versions (>=3.6) dicts actually keep their insertion order! So you could either use a normal dict or a collections.defaultdict (subclass of dict just like collections.Counter) to do this for you:

from collections import defaultdict

d = defaultdict(int)
for word in "This is one number and is a good number".split():
    d[word] += 1
defaultdict(<class 'int'>, {'This': 1, 'is': 2, 'one': 1, 'number': 2, 'and': 1, 'a': 1, 'good': 1})

Pure dict method:

d = {}

for word in "This is one number and is a good number".split():
    if word not in d:
        d[word] = 0
    d[word] += 1
{'This': 1, 'is': 2, 'one': 1, 'number': 2, 'and': 1, 'a': 1, 'good': 1}
xjcl
  • 12,848
  • 6
  • 67
  • 89
  • You will have to do `print(d)` at the end for the output to appear. You will also need to change my fixed string to `file.read()` – xjcl Feb 07 '22 at 23:25
  • Sorry, but i don't know how I can do it! The IDE only give me errors. – fpb_i Feb 07 '22 at 23:29
  • Where is your fixed string? – fpb_i Feb 07 '22 at 23:31
  • I mean you should replace `"This is one number and is a good number"` with `open('file.txt', encoding='utf-8').read()`. But first of all try to run my code 1-to-1 with a `print(d)` at the end. – xjcl Feb 07 '22 at 23:34
  • You need to unindent `print(d)` (remove spaces left of it) – xjcl Feb 07 '22 at 23:44
  • Oh Yeah! I got it! Thank you very much for your help! – fpb_i Feb 07 '22 at 23:45
  • Sure. (1) I think it makes sense to use my second block of code because it is easier to understand. Both code snippets do the same. (2) `defaultdict(int)` is like a dict but when you try to access a key that does not exist it creates a new one "by default" by creating a new `int` with value 0. This is just a convenience thing. – xjcl Feb 08 '22 at 00:11
  • Please consider accepting my answer if it solved your problem. – xjcl Feb 08 '22 at 15:54