喜欢的东西是否有使用String replace()方法来代替任何
sentence.replace(*, "newword")
(不工作,顺便说一句)的方式
比方说
sentence = "hello world" return sentence.replace(*, "newworld")
应该返回“新词新词”
喜欢的东西是否有使用String replace()方法来代替任何
sentence.replace(*, "newword")
(不工作,顺便说一句)的方式
比方说
sentence = "hello world" return sentence.replace(*, "newworld")
应该返回“新词新词”
由于您不会替换特定的单词,因此str.replace()
不会真正支持任何类型的模式匹配。
但是,你可以使用re.sub()
功能,让您在正则表达式会匹配一切,代替它传递:
import re
# Replace each series of non-space characters [^\s]+ with "newword"
sentence = re.sub('[^\s]+','newword',sentence)
例
你可以找到一个complete interactive example of this here和演示如下:
愚蠢的手指。谢谢,我相应地调整了它。 –
谢谢,Rion! – anquadros
你正在寻找的是一个字替换。因此,而不是替换字符的string.replace,你想要一些将替换所有单词的东西。
>>> sentence = "hello world this is my sentence"
>>> " ".join(["newword"] * len(sentence.split()))
'newword newword newword newword newword newword'
在上述情况下,我们吐涎句子到它的词汇列表,并制作简单字的另一列表的长度相同的“newword”。最后,我们要在它们之间
谢谢你,谢谢! – anquadros
的“”字加入了新的词放在一起如果你关心速度,只是手动各具特色的字符串似乎快两倍:
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
测试,所以我没有包括它)
谢谢,jayelm! – anquadros
什么'sentence.replace(*,“newword”)'返回? – vaultah
让我们说'句子=“hello world”',那么它应该返回'sentence ='newword newword'' – anquadros
尝试'sentence =''.join(['newword'] * len(sentence.split()))'' – vaultah