Python - Count number of words in a list strings

允我心安 提交于 2019-12-17 19:54:03

问题


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?


回答1:


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



回答2:


The simplest way should be

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



回答3:


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]



回答4:


for x,word in enumerate(mylist):
    print len(word.split())



回答5:


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



回答6:


We can count the number of a word's ocurrence in a 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)

Output:

Counter({mahesh:2},{hello:1},{nepal:1},{nikesh:2})




回答7:


This is another solution:

You can clean your data first and then count the result, something like that:

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))

The result:

4
1
2
3


来源:https://stackoverflow.com/questions/18827198/python-count-number-of-words-in-a-list-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!