Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Count number of words in a list strings

Im trying to find the number of whole words in a list of strings, heres the list

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

expected outcome:

4
1
2
3

There are 4 words in mylist[0], 1 in mylist[1] and so on

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

Totally doesnt work....

What do you guys think?

like image 829
Boosted_d16 Avatar asked Sep 16 '13 11:09

Boosted_d16


Video Answer


3 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
like image 104
Ashwini Chaudhary Avatar answered Sep 23 '22 11:09

Ashwini Chaudhary


The simplest way should be

num_words = [len(sentence.split()) for sentence in mylist]
like image 34
Hari Menon Avatar answered Sep 19 '22 11:09

Hari Menon


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]
like image 35
Franck Dernoncourt Avatar answered Sep 23 '22 11:09

Franck Dernoncourt