【问题标题】:Python: Is it possible to split sentence into two line?Python:是否可以将句子分成两行?
【发布时间】:2012-05-05 17:03:13
【问题描述】:
Sentence = "the heart was made to be broken"

如何使用 Python 拆分句子以在单独的行中显示? (每行 4 个字)

Line1: the heart was made
Line2: to be broken

有什么建议吗?

【问题讨论】:

  • 您是否只需要针对这个特定句子的解决方案,您是否有更普遍的问题?
  • 不适用于这个特定的句子。我有超过 50 个句子。
  • 我想我在上面说过我想每行显示 4 个单词。
  • 您将标点符号视为单独的单词(我希望不是)还是将它们视为单个单词的一部分。例如你的意思是“单词”吗?是一个词吗?
  • 你的问题是这个问题的修改版:stackoverflow.com/questions/1621906/…

标签: python


【解决方案1】:
【解决方案2】:

试试这个:

s = 'the heart was made to be broken'

for i, word in enumerate(s.split(), 1):
    if i % 4:
        print word,
    else:
        print word

> the heart was made
> to be broken

【讨论】:

    【解决方案3】:

    这里有一个解决方案:

    import math
    
    def fourword(s):
        words = s.split()
        fourcount = int(math.ceil(len(words)/4.0))
        for i in range(fourcount):
            print " ".join(words[i*4:(i+1)*4])
    
    if __name__=="__main__":
        fourword("This is a test of fourword")
        fourword("And another test of four")
    

    输出是:

    >python fourword.py 
    This is a test
    of fourword
    And another test of
    four
    

    【讨论】:

      【解决方案4】:

      让我解释一下使用itertools 模块的这个问题的解决方案。当您尝试处理序列时,无论是列表、字符串还是任何其他可迭代的,通常最好先看看标准库中的 itertools 模块

      from itertools import count, izip, islice, starmap
      
      # split sentence into words
      sentence = "the heart was made to be broken".split()
      # infinite indicies sequence -- (0, 4), (4, 8), (8, 12), ...
      indicies = izip(count(0, 4), count(4, 4)) 
      # map over indices with slicing
      for line in starmap(lambda x, y: sentence[x:y], indicies):
          line = " ".join(line)
          if not line:
              break
          print line
      

      【讨论】:

        【解决方案5】:

        通用函数:

        from itertools import count, groupby
        
        def split_lines(sentence, step=4):
            c = count()
            chunks = sentence.split()
            return [' '.join(g) for k, g in groupby(chunks, lambda i: c.next() // step)]
        

        你可以这样使用:

        >>> sentence = "the heart was made to be broken"
        >>> split_lines(sentence)
        ['the heart was made', 'to be broken']
        >>> split_lines(sentence, 5)
        ['the heart was made to', 'be broken']
        >>> split_lines(sentence, 2)
        ['the heart', 'was made', 'to be', 'broken']
        

        有了结果,你可以做任何你想做的事(包括打印):

        >>> for line in split_lines(sentence):
        ...     print line
        ...     
        the heart was made
        to be broken
        

        【讨论】:

        • 你可以对多个字符执行此操作吗?
        • @BenWebb 是的,您可以使用上面split_lines 函数的略微修改版本。而不是对chunks = sentence.split() 进行操作,而是直接对sentence 进行操作。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        • 2014-09-02
        • 2010-11-26
        • 1970-01-01
        • 2020-10-03
        相关资源
        最近更新 更多