0 votes
1 view
in Python by (8.3k points)

I am doing a per-word character-counter from a user input.

However, it seems that if there are duplicate words (of the similar case) from the input, my codes will only output the first word (the duplicates will not be included).

I have used the split, len and for loop for this.

sentence = input("Enter a sentence: ")

splitting = sentence.split()

final = {x:len(x) for x in splitting}

print(final)

  • Sample input: New phone alert! Your new phone will be available next week.

  • Expected output: {'New': 3, 'phone': 5, 'alert!': 6, 'Your': 4, 'new': 3, 'phone': 5, 'will': 4, 'be': 2 ...}

  • Actual output: {'New': 3, 'phone': 5, 'alert!': 6, 'Your': 4, 'new': 3, 'will': 4, 'be': 2 ...}

It shows both 'New' and 'new' as their cases don't match. However, 'phone' is displayed only once.

1 Answer

0 votes
by (16.8k points)

You can get word, characterCount in that word in a list of list.

listOfList = [[x , len(x)] for x in splitting]

print(listOfList)

Result:

[['New', 3], ['phone', 5], ['alert!', 6], ['Your', 4], ['new', 3], ['phone', 5], ['will', 4], ['be', 2], ['available', 9], ['next', 4], ['week.', 5]]

...