繁体   English   中英

"将句子列表替换为文本"

[英]replace list of sentence to the text

如果文本包含来自list1<\/code>的句子,我正在尝试替换它。

我尝试了以下代码,但它不起作用:

text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
  if i in text:
    text.replace(i,"")

#wrong output:
'what a lovely car it is , i love it by the way it looks and the color is so good. i am feeling very happy after seeing it'

Python字符串是不可变的<\/a>; str.replace()<\/code>方法不会更改现有<\/em>字符串,而是根据现有字符串返回一个新<\/em>字符串。

所以只需将text.replace(i,"")<\/code>替换为text = text.replace(i,"")<\/code> 。 观察:

text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

for i in list1:
  if i in text:
    text = text.replace(i, "")

print(text)

str.replace<\/code>返回一个新字符串(字符串无论如何都是不可变的),因此您需要重新分配:

for to_replace in list1:
    text = text.replace(to_replace, "")

replace 将创建一个新字符串,因此请使用。

text = text.replace(i,"")

您几乎是正确的,唯一的错误是语句: , text.replace()<\/code>此函数不会更改原始变量,它返回的对象是原始对象的副本,因此您需要将其分配给 text . 代码:

text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
    if i in text:
        text = text.replace(i,"")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM