2

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)
greenszpila
  • 193
  • 1
  • 1
  • 14
  • if you need to count words in each element of the list then shouldn't the output be 3,4,0 – Sarthak Kumar Jan 26 '20 at 21:36
  • Does this answer your question? [How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?](https://stackoverflow.com/questions/19410018/how-to-count-the-number-of-words-in-a-sentence-ignoring-numbers-punctuation-an) – AMC Jan 26 '20 at 23:08

5 Answers5

3

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]
YOLO
  • 20,181
  • 5
  • 20
  • 40
1

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
Jordan Brière
  • 1,045
  • 6
  • 8
1

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.

Juha Untinen
  • 1,806
  • 1
  • 24
  • 40
0

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]

Sarthak Kumar
  • 304
  • 5
  • 16
0

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]
Giannis Clipper
  • 707
  • 5
  • 9