Search code examples
pythonlistcounting

python how to count words in a list element


below code returns a list:

[['We test robots'], ['Give us a try'], [' ']]

now I need to count words in each element, how could I achieve this in Python without importing any packages. In the above I should get 3,4 and 1 for three list elements. thanks

import re
S ="We test robots.Give us a try? "

splitted = [l.split(',') for l in (re.split('\.|\!|\?',S)) if l]

print (splitted)

Solution

  • for calculating words in each elements

    import re
    S ="We test robots.Give us a try? "
    
    splitted = [l.split(',') for l in (re.split('\.|\!|\?',S)) if l]
    
    item =[]
    for i in splitted:
        item.append(len(i[0].split()))
    
    print(item)
    

    output will be [3,4,0]