In [8]: import re
In [9]: sentence = "hello world this is my sentence"
In [10]: nonspace = re.compile('[^\s]+')
In [11]: %timeit re.sub(nonspace, 'newword', sentence)
100000 loops, best of 3: 6.28 µs per loop
In [12]: %timeit ' '.join('newword' for _ in xrange(len(sentence.split())))
100000 loops, best of 3: 2.52 µs per loop
In [13]: sentence *= 40 # Make the sentence longer
In [14]: %timeit re.sub(nonspace, 'newword', sentence)
10000 loops, best of 3: 70.6 µs per loop
In [15]: %timeit ' '.join('newword' for _ in xrange(len(sentence.split())))
10000 loops, best of 3: 30.2 µs per loop
而且join实际上是faster when you hand it a list,因此' '.join(['newword' for _ in xrange(len(sentence.split()))])应该会带来一些性能改进(它将结果缓存在非正式的%timeit测试中,所以我没有包含它)
因为您不打算替换特定的单词,^{} 实际上不支持任何类型的模式匹配。你知道吗
但是,您可以使用^{} 函数,该函数允许您传入一个与所有内容匹配的正则表达式并替换它:
示例
您可以找到complete interactive example of this here并在下面演示:
你要找的是一个替换词。所以字符串.替换如果要替换字符,则需要替换所有单词的内容。你知道吗
在上面的例子中,我们将这个句子放入一个单词列表中,然后简单地列出另一个相同长度的单词“newword”。最后,我们把生词和它们之间的“”字符连接起来
如果你关心速度,仅仅手工制作字符串似乎要快一倍:
而且
join
实际上是faster when you hand it a list,因此' '.join(['newword' for _ in xrange(len(sentence.split()))])
应该会带来一些性能改进(它将结果缓存在非正式的%timeit
测试中,所以我没有包含它)相关问题 更多 >
编程相关推荐