python中有字符串折叠库函数吗?
是否有跨平台库函数可以将多行字符串折叠为不带重复空格的单行字符串?
我在下面想出了一些片段,但我想知道是否有一个我可以导入的标准函数,甚至可能在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
会做这项工作。
'\n'
是Python中通用的行结束符。will do the job.
'\n'
is a universal end of line character in python.你的想法是正确的,你只需要更仔细地阅读 python 手册:
You had the right idea, you just needed to read the python manual a little more closely:
内置的 string.split() 方法将根据空格进行分割,因此您可以使用它,然后使用空格连接结果列表,如下所示:
这是一个完整的测试脚本:
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:Here's a complete test script: