Python - 计算列表字符串中的单词数

时间:2013-09-16 11:45:47

标签: python string list counter

我试图在字符串列表中找到整个单词的数量,这是列表

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

预期结果:

4
1
2
3

mylist [0]中有4个单词,mylist [1]中有1个,依此类推

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

完全不起作用....

你们有什么想法?

8 个答案:

答案 0 :(得分:18)

使用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

答案 1 :(得分:3)

最简单的方法应该是

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

答案 2 :(得分:2)

您可以使用NLTK

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

输出:

[4, 1, 2, 3]

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

我们可以使用Counter函数在列表中计算单词的出现次数。

from collection import Counter

string = ["mahesh","hello","nepal","nikesh","mahesh","nikesh"]

count_each_word = Counter(string)
print(count_each_word)

输出:

  

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

答案 6 :(得分:0)

这是另一种解决方案:

您可以先清除数据,然后计算结果,诸如此类:

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

结果:

4
1
2
3

答案 7 :(得分:0)

mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"]
flage = True
for string1 in mylist:
    n = 0
    for s in range(len(string1)):
        if string1[s] == ' ' and flage == False:
            n+=1
        if string1[s] == ' ':
            flage = True
        else:
            flage = False
    print(n+1)