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

9

我正在尝试找出一组字符串中的整个单词数量,以下是这组字符串:

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

完全不起作用... 你们觉得怎么样?

9个回答

21

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

6
最简单的方法应该是:
num_words = [len(sentence.split()) for sentence in mylist]

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]

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)

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

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

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

1
请格式化您的代码并解释您的答案在其他答案中提供了什么附加价值。 - Andrejs
如果您想计算唯一单词,可以使用集合。简单地说,它是 len(set(a.split())) - Mohammad ElNesr

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


从集合中导入(注意末尾的S) - ruslaniv

0
lista="Write a Python function to count the number of occurrences of a given characte Write a  of occurrences of a given characte"

dic=lista.split(" ")
wcount={} 
for i in dic:
  if i  in wcount:
    wcount[i]+=1
  else:
    wcount[i]=1 
print(wcount)

带有解决方案的图片


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接