【发布时间】:2021-09-15 02:32:39
【问题描述】:
我知道有很多方法可以替换句子中的字符串,例如:
sentences= 'This is a sentence, even there may be a lot of sentence coming'
word_list = ["sentence", 'be', 'coming']
to_replace = ["changes"]
res = ' '.join([to_replace if idx in word_list else idx for idx in sentences.split()])
print("After replace: " + str(res))
output: 'This is a changes, even there may changes a lot of
sentence changes'
但我想要的是:
sentence = 'This is a sentence, even there may be a lot of sentence coming'
word_list = ["sentence", 'be', 'coming']
to_replace = ['change1', 'change2', 'change3']
所以输出应该是这样的:
output: 'This is a change1, even there may change2 a lot of sentence change3'
是否可以仅用字符串(word_list)中的给定字符串(to_replace)而不是句子中的其他单词替换句子,即使句子中可能有重复的单词?说“句子”重复了两次,但我只想替换一次,而不是所有单词“句子”
更新:
k = []
dummy = 'Lorem what your doing ? how are you guys doing ? dummy
me doing bad '
for p1 in x1:
for n1, n2 in zip(['Lorem', 'dummy'], ['hello', 'hai']):
new = p1.replace(n1, n2)
k.append(new)
output: ['hello what your doing ? how are you guys doing ? dummy
me doing bad ',
'Lorem what your doing ? how are you guys doing ? hai
me doing bad ']
在上面的例句中重复出现。请帮忙,我只想要一句话。
【问题讨论】:
-
是的,当然。当你尝试这样做时有什么特别的困难吗?
-
一个明显的解决方案是遍历句子中的所有单词,如果它与当前要替换的单词匹配,则替换它并前进到下一个要替换的单词。
-
是的,有一些困难。我更新了我的代码请检查
-
我已经更新了我正在处理的额外代码,请帮忙。
-
我在下面显示。 replace 方法中还有另一个参数,您可以在其中指定对每个单词进行多少次替换。此外,您不必拆分和加入字符串。只需使用原始字符串并创建一个具有相同名称的新对象。
标签: python arrays regex string sorting