python中有字符串折叠库函数吗?

发布于 2024-07-30 20:05:43 字数 481 浏览 10 评论 0原文

是否有跨平台库函数可以将多行字符串折叠为不带重复空格的单行字符串?

我在下面想出了一些片段,但我想知道是否有一个我可以导入的标准函数,甚至可能在 C 中进行了优化?

def collapse(input):
    import re
    rn = re.compile(r'(\r\n)+')
    r = re.compile(r'\r+')
    n = re.compile(r'\n+')
    s = re.compile(r'\ +')
    return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input))))

PS 感谢您的良好观察。 ' '.join(input.split()) 似乎是赢家,因为在我的例子中,与使用预编译的 r'\s+'< 进行搜索替换相比,它实际上运行速度大约是两倍/代码> 正则表达式。

Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?

I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps even optimized in C?

def collapse(input):
    import re
    rn = re.compile(r'(\r\n)+')
    r = re.compile(r'\r+')
    n = re.compile(r'\n+')
    s = re.compile(r'\ +')
    return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input))))

P.S. Thanks for good observations. ' '.join(input.split()) seems to be the winner as it actually runs faster about twice in my case compared to search-replace with a precompiled r'\s+' regex.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暖阳 2024-08-06 20:05:44
multi_line.replace('\n', '')

会做这项工作。 '\n' 是Python中通用的行结束符。

multi_line.replace('\n', '')

will do the job. '\n' is a universal end of line character in python.

陌路黄昏 2024-08-06 20:05:44

你的想法是正确的,你只需要更仔细地阅读 python 手册:

import re
somewhitespace = re.compile(r'\s+')
TEST = """This
is        a test\twith a
  mix of\ttabs,     newlines and repeating
whitespace"""

somewhitespace.sub(' ', TEST)

'This is a test with a mix of tabs, newlines and repeating whitespace'

You had the right idea, you just needed to read the python manual a little more closely:

import re
somewhitespace = re.compile(r'\s+')
TEST = """This
is        a test\twith a
  mix of\ttabs,     newlines and repeating
whitespace"""

somewhitespace.sub(' ', TEST)

'This is a test with a mix of tabs, newlines and repeating whitespace'
故乡的云 2024-08-06 20:05:44

内置的 string.split() 方法将根据空格进行分割,因此您可以使用它,然后使用空格连接结果列表,如下所示:

' '.join(my_string.split())

这是一个完整的测试脚本:

TEST = """This
is        a test\twith a
  mix of\ttabs,     newlines and repeating
whitespace"""

print ' '.join(TEST.split())
# Prints:
# This is a test with a mix of tabs, newlines and repeating whitespace

The built-in string.split() method will split on runs of whitespace, so you can use that and then join the resulting list using spaces, like this:

' '.join(my_string.split())

Here's a complete test script:

TEST = """This
is        a test\twith a
  mix of\ttabs,     newlines and repeating
whitespace"""

print ' '.join(TEST.split())
# Prints:
# This is a test with a mix of tabs, newlines and repeating whitespace
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文