喜歡的東西是否有使用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