Skip to content Skip to sidebar Skip to footer

Number Of Space Between Each Word

How can I find a quick way to count the number of spacing between each word in a text? Each space represents a value, Example: one space is the letter 'a', two spaces is the letter

Solution 1:

import re
import string

''.join(map(lambda x: string.lowercase[len(x) - 1], re.findall(r'\s+', 'hello all  the   world')))
# 'abc'

Solution 2:

For entertainment value -- and because I don't like regular expressions but do like the itertools module -- another way to do this is to know that you can use itertools.groupby to collect objects by like kind:

>>>from string import lowercase>>>from itertools import groupby>>>>>>s = 'hello all  the   world'>>>counts = [(len(list(cpart))) for c,cpart in groupby(s) if c == ' ']>>>counts
[1, 2, 3]
>>>values = [lowercase[count-1] for count in counts]>>>values
['a', 'b', 'c']
>>>vs = ''.join(values)>>>vs
'abc'

itertools.groupby is often very useful.

Solution 3:

Assuming i got you right:

fromstringimport lowercase

word = lowercase[:text.count(' ')]

Solution 4:

If you'd specify the output format you want, I could make this more specific, but this should put you well on your way to a complete solution.

import re

word_re = re.compile('(\W*)(\w+)'):

formatchin word_re.finditer(text)
    spaces, word = match.groups()
    printlen(spaces), word

Note: \w stands for "word characters" and \W is the opposite. Depending on your exact problem you may want to make these more specific.

Reference: http://docs.python.org/library/re.html#regular-expression-syntax

Post a Comment for "Number Of Space Between Each Word"