number of space between each word

核能气质少年 提交于 2019-12-11 05:37:45

问题


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 'b', etc..

An example with the text

text :

hello all  the   world 

one space between hello and all --> 'a', two spaces between all and the --> 'b', ...

word --> 'abc'


回答1:


import re
import string

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



回答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.




回答3:


Assuming i got you right:

from string import lowercase

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



回答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+)'):

for match in word_re.finditer(text)
    spaces, word = match.groups()
    print len(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



来源:https://stackoverflow.com/questions/8864795/number-of-space-between-each-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!