5

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

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

完全不行……

你们有什么感想?

4

8 回答 8

19

使用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
于 2013-09-16T11:50:45.933 回答
4

最简单的方法应该是

num_words = [len(sentence.split()) for sentence in mylist]
于 2013-09-16T11:50:11.003 回答
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]
于 2015-08-11T23:58:58.717 回答
0
for x,word in enumerate(mylist):
    print len(word.split())
于 2013-09-16T12:12:41.037 回答
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
于 2019-08-26T16:38:07.010 回答
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)
于 2020-03-11T19:55:57.450 回答
0

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

from collection import Counter

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

count_each_word = Counter(string)
print(count_each_word)

输出:

计数器({mahesh:2},{hello:1},{nepal:1},{nikesh:2})

于 2019-05-16T01:31:37.750 回答
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
于 2016-09-13T10:30:57.347 回答