用python中的某个单词替换单词列表

2024-06-12 08:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

比如说,如果我有一个段落,我想找到并用一个特定的单词替换其中的特定单词

在定义单词列表之后,我尝试使用for循环来实现这一点

这是我的密码

script = """ In this sense, netting can represent , which gives Howie return on Zachary."""

ROE = ["In", "this"] #the word list I'm defining (the list of words I want it replaced)
for ROE in script: 
 script.replace(ROE, "ROE")

#desired output = ROE ROE sense, netting can represent , which gives Howie return on Zachary.

真的不行,有人能帮我修一下吗


Tags: inwhichforreturnonscriptthis单词
3条回答

Python中的字符串str数据类型是不可变的。这意味着,如果要更改字符串,基本上必须创建一个具有更改的新字符串,然后可以将结果分配给变量

当然,您可以将结果分配给原始字符串分配给的同一变量,该变量可能具有对旧字符串的最后一次引用,从而使其得到清理。但在很短的时间内,字符串总会有一个新的副本

例如:

s = 'Hello'
s += ' world!'
print(s)

这似乎是用'Hello'' world!'添加到现有的s上,但它实际上只是创建一个新字符串'Hello world!',并将其分配给s,替换旧字符串

在您的例子中,这解释了为什么不能只调用字符串上的.replace()并期望它改变。相反,该方法返回所需的新字符串,您可以将其分配给变量:

script = """ In this sense, netting can represent , which gives Howie return on Zachary."""

roe = ["In", "this"]
for word_to_replace in roe: 
    script = script.replace(word_to_replace, 'ROE')

(请注意,还有一些其他问题,但上述问题应该可以解决)

您有几个问题:

  1. 你不是在要替换的单词列表上循环,而是在script中的字符上循环
  2. 您没有在任何地方分配replace的结果。这不是就地操作,因为字符串是不可变的
  3. 您正在重新分配ROE变量
for word in ROE:
    script = script.replace(word, 'ROE')

注意replace()对单词边界一无所知。您的代码将Inside转换为ROEside。如果您想做得更好,可以使用正则表达式并将单词包装在\b边界中。正则表达式还允许您一次执行所有替换

import re

regex = re.compile(r'\b(?:' + '|'.join(re.escape(word) for word in ROE) + r')\b')
script = regex.sub('ROE', script)

这将创建一个正则表达式\b(?:In|this)\b,它匹配任意一个单词

我找到了一个相对容易的解决方案

stopwords=['In','this','to']
for i in stopwords:
 n=a.replace(i,'ROE')
 a=n

我得到了这个链接的帮助:Removing list of words from a string

相关问题 更多 >