【问题标题】:Python: How to extract only complete words in a character chunk of x characters?Python:如何仅提取 x 个字符的字符块中的完整单词?
【发布时间】:2018-06-17 15:47:57
【问题描述】:

考虑字符串 s = "you'll never know the truth"

如果我想将此字符串拆分为 15 个字符 (s[:15]),我会得到 "you'll never kn"

我想对这个新字符串做的只是提取 complete 单词(在这种情况下是“you'll”和“never”),然后返回该字符串,以及我的方法循环从不完整单词的开头开始。知道怎么做吗?

编辑:正如 PM 2Ring 所提到的,我目前只关心作为单词分隔符的间距。一旦我弄清楚了,我将处理逗号、连字符、换行符等。

提前致谢!

【问题讨论】:

  • 空格是我们需要测试的only单词分隔符吗?或者我们是否还需要处理诸如不间断空格、连字符、制表符、换行符之类的东西......?我们如何处理包含超过 15 个字符的单词?
  • pneumonoultramicroscopicsilicovolcanoconiosis 是一个词!
  • @PM2Ring,感谢您收听。是的,现在我只关心作为主要分隔符的空格。当我弄清楚这一点时,我会处理你提到的其余部分。
  • @InAFlash 我们在这里不必担心。我们只需要寻找分隔单词的空格。
  • @InAFlash 然后他想重复这个过程,这样他就可以捕捉到“知道”。等等。

标签: python string loops


【解决方案1】:

您可以使用标准库的textwrap 模块。

import textwrap

s = "you'll never know the truth, said the artificially emlengthened example string"

for chunk in textwrap.wrap(s, 15):
    print(chunk)

输出

you'll never
know the truth,
said the
artificially
emlengthened
example string

【讨论】:

  • 太棒了,正是我需要的,非常感谢!我是编程新手,这是我的第一个应用程序,了解所有标准库的模块和方法只是花时间编码的问题吗?
  • 了解工具箱中存在的工具是值得的,但不值得将它们的每一个细节都牢记在心。我建议至少浏览一下 Python 库参考 :)
【解决方案2】:

执行此操作的一种简单方法是切掉所需最大块大小(在本例中为 15)的子字符串,并使用 str.rfind 方法定位最后一个空间。如果我们没有找到空格,则吐出整个块。

一个很好的 Pythonic 方法是在生成器中。

def word_split(src, chunksize):
    # Clean up any newlines and duplicate spaces
    src = ' '.join(src.split())
    while src:
        chunk = src[:chunksize]
        idx = chunk.rfind(' ')
        if idx == -1:
            # no space found
            idx = chunksize
        yield chunk[:idx]
        src = src[idx+1:]

# test

src = """you'll never know  the truth, or a way for my   loop
to start at the beginning of  the incomplete word like this
pneumonoultramicroscopicsilicovolcanoconiosis"""
chunksize = 15

for s in word_split(src, chunksize):
    print(repr(s), len(s))

输出

"you'll never" 12
'know the' 8
'truth, or a' 11
'way for my' 10
'loop to start' 13
'at the' 6
'beginning of' 12
'the incomplete' 14
'word like this' 14
'pneumonoultrami' 15
'roscopicsilicov' 15
'lcanoconiosis' 13

【讨论】:

  • 我认为,根据他在 OP 中的最后评论,他还希望你忽略非英语单词,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 2022-06-14
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
相关资源
最近更新 更多