【问题标题】:number of space between each word每个单词之间的空格数
【发布时间】:2012-01-14 19:34:09
【问题描述】:

如何找到一种快速计算文本中每个单词之间的间距数的方法?

每个空格代表一个值,

例如:一个空格是字母'a',两个空格是字母'b',等等。

文本示例

文字:

hello all  the   world 

hello 和 all 之间有一个空格 --> 'a', all 和 the 之间有两个空格 --> 'b', ...

单词 --> 'abc'

【问题讨论】:

  • text : "hello all the world" one space between hello and all --> 'a', two spaces between all and the --> 'b', ... - 我不明白那个例子的最后一部分。我只能在例句中的每个单词之间看到一个空格。
  • @birryree 如果你看源码,他似乎输入了“hello_all__the___world”,但编辑器并没有显示多余的空格。
  • @brc - 哦,我现在看到了 - JBernardo 编辑了它,我猜只有代码模式适用于多间距。

标签: python numbers word


【解决方案1】:
import re
import string

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

【讨论】:

    【解决方案2】:

    出于娱乐价值——而且因为我不喜欢正则表达式但喜欢 itertools 模块——另一种方法是知道您可以使用 itertools.groupby 按同类收集对象:

    >>> 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 通常非常有用。

    【讨论】:

    • 喜欢你的回答胜过我的:)
    【解决方案3】:

    假设我猜对了:

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

    【讨论】:

      【解决方案4】:

      如果您指定所需的输出格式,我可以更具体地说明,但这应该会让您顺利找到完整的解决方案。

      import re
      
      word_re = re.compile('(\W*)(\w+)'):
      
      for match in word_re.finditer(text)
          spaces, word = match.groups()
          print len(spaces), word
      

      注意:\w 代表“单词字符”,\W 则相反。根据您的具体问题,您可能希望使这些更具体。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-14
        • 2011-05-29
        • 2014-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        相关资源
        最近更新 更多