greenszpila
greenszpila

Reputation: 203

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)

Upvotes: 2

Views: 1291

Answers (5)

Giannis Clipper
Giannis Clipper

Reputation: 707

Just practicing...

def word_counter(passlist):
    do_count = lambda x: len(x.split())
    result=[]

    for elem in passlist:
        if isinstance(elem, list):
            result += [word_counter(elem)]
        elif isinstance(elem, str):
            result += [do_count(elem)]

    return result

print(word_counter([['We test robots'], ['Give us a try'], [' ']]))
# output: [[3], [4], [0]]

print(word_counter(['First of all', ['One more test'], [['Trying different list levels'], [' ']], 'Something more here']))
# output: [3, [3], [[4], [0]], 3]

Upvotes: 0

Juha Untinen
Juha Untinen

Reputation: 1887

If all your input elements are lists, and all delimiters are spaces, then you can do this without importing anything:

input = [['We test robots'], ['Give us a try'], [' ']]
output = []

for item in input:
   output.append(len(item[0].split()))

print(output)  # [3, 4, 0]

If you want an empty item to print 1 instead of 0, just check if the value is 0.

Upvotes: 1

YOLO
YOLO

Reputation: 21759

There are multiple ways to do this, here's two:

# using map
list(map(lambda x: len(x[0].split()) if len(x[0]) > 1 else 1, l))

[3, 4, 1]

# using list comprehension
[len(x[0].split()) if len(x[0]) > 1 else 1 for x in l]

[3, 4, 1]

Upvotes: 3

Sarthak Kumar
Sarthak Kumar

Reputation: 304

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]

Upvotes: 0

Jordan Brière
Jordan Brière

Reputation: 1070

I assume you want to do something like:

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

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

print(splitted)

for sentence in splitted:
    count = len(sentence[0].split())
    if not count and sentence[0]:
        count += 1
    print(count)

Would prints:

[['We test robots'], ['Give us a try'], [' ']]
3
4
1

Upvotes: 1

Related Questions