我想在不使用正則運算式的情況下用另一個字串替換整個單詞。做我想要的replace_all_whole_words1,但我不想使用正則運算式,只用于測驗我的replace_all_whole_words2函式是否正常作業(不是)。
import re
def replace_all_whole_words1(needle, replacement, haystack):
needle = re.escape(needle)
return re.sub(r"\b%s\b" % needle, replacement, haystack)
def replace_all_whole_words2(needle, replacement, haystack):
i=0
while len(haystack) > i:
found_word = False
found_word_start = i
found_word_end = 0
found_type = 0 # will repersent if we found, word " " or " " word or " " word " " ()
if i == 0:
found_word = haystack[i:i len(needle " " )] == needle " "
found_word_end = i len(needle)
found_type = 1
elif i == len(haystack) - len(" " needle):
found_word = haystack[i:i len(" " needle)] == " " needle
found_word_end = i len(" " needle)
found_type = 2
else:
found_word = haystack[i:i len(" " needle " " )] == " " needle " "
found_word_end = i len(" " needle " ")
found_type = 3
if found_word:
print(haystack, found_word_start, found_word_end, i, found_type)
haystack = haystack[:found_word_start] replacement haystack[found_word_end:]
i = 1
return haystack
needle = "test"
replacement = "replaced"
haystack = "test test test testa atest"
print(
replace_all_whole_words1(needle, replacement, haystack) == replace_all_whole_words2(needle, replacement, haystack)
)
print(
replace_all_whole_words2(needle, replacement, haystack)
)
uj5u.com熱心網友回復:
這里已經有幾個很棒且更簡單的答案,它們可以將 haystack 轉換為串列,執行替換,然后將其轉換回字串。如果您仍然想始終使用 haystack 作為字串,請查看我制作的這個解決方案。
def replace_all_whole_words2(needle, replacement, haystack):
# Counter to go through characters in haystack
i = 0
# This will collect all chars separated by space as word
word = ''
# len_needle will control replacement insertion and diff will adjust i after insertion
len_needle = len(needle)
diff = len(replacement) - len_needle
# Go through characters in haystack and replace needle with replacement
while i < len(haystack):
char = haystack[i]
if char == ' ':
if word == needle:
haystack = haystack[:(i-len_needle)] replacement haystack[i:]
# Adjust i so that you can continue from the next char after the space
i = diff
# Reset word to collect new chars
word = ''
else:
word = char
i = 1
return haystack
測驗:
needle = "test"
replacement = "replacement"
haystack = "test test test testa atest"
replace_all_whole_words2(needle, replacement, haystack)
輸出:
'replacement replacement replacement testa atest'
uj5u.com熱心網友回復:
為什么不轉換為串列?因為您只是在洗掉單詞。
def replace_all_whole_words2(needle, replacement, haystack):
l = haystack.split()
for idx, word in enumerate(l):
if word == needle:
l[idx] = replacement
return ' '.join(l)
uj5u.com熱心網友回復:
正如評論中所解釋的,使用拆分分離,使用串列理解然后重新加入:
def replace_all_whole_words2(needle, replacement, haystack):
word_list = haystack.split(' ')
new_list = [replacement if word == needle else word for
word in word_list]
return " ".join(new_list)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448796.html
