Python - count the number of words in list lines

I'm trying to find the number of integer words in a list of strings, heres list

mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"] 

Expected Result:

 4 1 2 3 

There are 4 words [0] in my list, 1 in my list [1], etc.

 for x, word in enumerate(mylist): for i, subwords in enumerate(word): print i 

Completely not working ....

What do you guys think?

+4
source share
7 answers

Use str.split :

 >>> mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"] >>> for item in mylist: ... print len(item.split()) ... 4 1 2 3 
+18
source

The easiest way -

 num_words = [len(sentence.split()) for sentence in mylist] 
+3
source

You can use NLTK :

 import nltk mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"] print(map(len, map(nltk.word_tokenize, mylist))) 

Output:

 [4, 1, 2, 3] 
+2
source
 for x,word in enumerate(mylist): print len(word.split()) 
0
source
 a="hello world aa aa aa abcd hello double int float float hello" words=a.split(" ") words dic={} for word in words: if dic.has_key(word): dic[word]=dic[word]+1 else: dic[word]=1 dic 
0
source

We can count the number of occurrences of a word in the list using the Counter function.

 from collection import Counter string = ["mahesh","hello","nepal","nikesh","mahesh","nikesh"] count_each_word = Counter(string) print(count_each_word) 

Exit:

Counter ({Mahesh: 2}, {Hello: 1}, {Nepal: 1}, {Nikesh: 2})

0
source

This is another solution:

You can clear your data first and then calculate the result, something like this:

 mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"] for item in mylist: for char in "-.,": item = item.replace(char, '') item_word_list = item.split() print(len(item_word_list)) 

Result:

 4 1 2 3 
0
source

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


All Articles