【问题标题】:Include full words in string slicing在字符串切片中包含完整的单词
【发布时间】:2013-11-07 06:54:28
【问题描述】:

这是我的一些代码:

def breakUp(x,chunk_size):
    return [ x[i:i+chunk_size] for i in range(0, len(x), chunk_size) ]

它是这样工作的:

In [8]: breakUp('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!',10)

Out[8]: 
['This is a ',
 'cool sente',
 'nce... How',
 ' about eat',
 'ing it??? ',
 'Whats more',
 '?? pepper ',
 'is availab',
 'le all for',
 ' free!!!']

但是正如你在第二个元素中看到的,句子这个词没有被完全理解,它说“sente”......

我知道这是因为我已经要求 python 在每 10 个字符之后分割它......无论如何指定我想在每 10 个字符之后分割,但如果是第 10 个字符。以一个单词结尾,取整个单词...?

【问题讨论】:

  • 这听起来像是家庭作业,但我会将行拆分为单词(定义为用空格分隔的字母),然后添加单词和空格,直到 >= chunk_size。
  • 不,但我希望块是 x characters 长...我知道提到的约束会导致半字。但我现在想要的是块应该是大约。 x 字符 长。我可以承受在两边移动一些字符以吞没不合适的单词
  • 然后算出你可以作为一个数字允许多少模糊,将这些词加到一个字符串中,然后检查len,看看它是否在你的+-chunk_size范围内。跨度>

标签: python string loops


【解决方案1】:

包括电池:

>>> import textwrap
>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 15)
This is a cool
sentence... How
about eating
it??? Whats
more?? pepper
is available
all for free!!!

这几乎可以满足您的所有要求。除了如果您将10 指定为第二个参数,它仍然会拆分sentence...,因为无法将其放入10 个字符中。但是,如果你想这样做,你可以自定义textwrapbreak_long_words=False

>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 10, break_long_words=False)
This is a
cool
sentence...
How about
eating
it???
Whats
more??
pepper is
available
all for
free!!!

【讨论】:

  • 伙计,你解决了我的问题......!!除了print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 15).split('\n') 会给我我想要的..!!现在编辑你的答案接受!!!
  • @tenstar 我在演示中使用了textwrap.fill。如果您不需要换行符,只需使用textwrap.wrap - 请参阅文档docs.python.org/2/library/textwrap.html
猜你喜欢
  • 2019-11-20
  • 2015-11-22
  • 2019-01-29
  • 2018-11-23
  • 2019-08-25
  • 2018-01-08
  • 2019-07-25
  • 2015-05-21
  • 1970-01-01
相关资源
最近更新 更多