Dictionary of words

My home problem is to write a Python function called LetterCount () that takes a string as an argument and returns a dictionary of the number of letters. However, my code includes space and commas as part of a dictionary that I don't want. Could you help me. How to remove empty space from my list? Here is my code?

import string def LetterCount(str): str= str.lower().strip() str = str.strip(string.punctuation) list1=list(str) lcDict= {} for l in list1: if l in lcDict: lcDict[l] +=1 else: lcDict[l]= 1 print lcDict LetterCount("Abracadabra, Monsignor") 
+4
source share
7 answers

You can also check if l is a literal character ( if l.isalpha() )

Example:

  import string def LetterCount(str): str= str.lower().strip() str = str.strip(string.punctuation) list1=list(str) lcDict= {} for l in list1: if l.isalpha(): if l in lcDict: lcDict[l] +=1 else: lcDict[l]= 1 print lcDict LetterCount("Abracadabra, Monsignor") 
+2
source

Python extension - Letter Count Dict :

 from collections import Counter def LetterCount(text): return Counter(c for c in text.lower() if c.isalpha()) 
+3
source

Before you assign an account to the else branch, you must check if l letter. Assign an invoice only if it is a letter.

+1
source

From a python document (pay attention to the front and back aspects):

string.strip (s [, chars]) Return a copy of the string with leading and deleted characters. If characters are omitted or None, whitespace characters are deleted. If given and not None, the characters must be a string; characters in the string will be stripped from both ends of the string this method is called.

Changed in version 2.2.3: Symbols option has been added. Fonts parameter cannot be passed before version 2.2.

You should take a look at str.replace () and DefaultDict :)

+1
source

You want str.translate instead of str.strip .

+1
source

Another option is to remove all non-alphabetic characters from the string using filter() :

 filter(str.isalpha, "Abracadabra, Monsignor") 'AbracadabraMonsignor' 

(be careful when using this in your code - you have obscured the built-in str variable with the same name. Never call the str variable.)

+1
source

I don’t want to do my homework for you because I don’t understand that this will help you, but I will try to help you in the right direction, try this:

 alphabet = map(chr, range(97, 123)) 

or

 alphabet2 = list(string.lowercase) 

alphabet and alphabet2 will contain all lowercase letters of the alphabet in the list.

Thanks eumiro for the rest!

0
source

Source: https://habr.com/ru/post/1348107/


All Articles