如何在Python中替换文本数组中的单词?

如何在Python中替换文本数组中的单词?,python,numpy,nlp,stemming,Python,Numpy,Nlp,Stemming,我想用我自己的数组来阻止我的文本: word_list1=[“cccc”、“bbbb”、“aaa”] def stem_文本(文本): text=text.split() array=np.array(文本) temp=np.where(数组==word\u list1,word\u list1[0],数组) text=''。连接(临时) 返回文本 我想这样做: 对于word\u list 1中的所有单词,请检查文本,如果某些单词匹配,请将其替换为word\u list[0]您可以使用列表理解

我想用我自己的数组来阻止我的文本:

word_list1=[“cccc”、“bbbb”、“aaa”]
def stem_文本(文本):
text=text.split()
array=np.array(文本)
temp=np.where(数组==word\u list1,word\u list1[0],数组)
text=''。连接(临时)
返回文本
我想这样做:


对于
word\u list 1
中的所有单词,请检查文本,如果某些单词匹配,请将其替换为
word\u list[0]

您可以使用列表理解

word_list1 = ["cccc", "bbbb", "aaa"]

def stem_text(text):
    text = text.split()
    temp = [word_list1[0] if i in word_list1 else i for i in text]
    text = ' '.join(temp)
    return text

stem_text("hello bbbb now aaa den kkk")
输出:

'hello cccc now cccc den kkk'

你可以在上面运行一个替换。如果它存在(
如果文本中有关键字
),它将被替换。但是,如果它不存在,replace函数将不起任何作用,因此也可以。因此,if条件是不必要的。

假设您有一个要替换为“cccc”的单词列表和一个字符串,您希望在其中查找这些单词并替换它们

words_to_replace = [...]
word_list1 = ["cccc", "bbbb", "aaa"]
string = 'String'
for word in words_to_replace:
   new_string = string.replace(word, words_list1[0])
   string = new_string

提供预期output@AkshayNevrekar我怎么做?我是Python中的新手,您可以考虑在清单理解中使用一个用于<代码> WordsList1的检查集。否则,您需要在每次迭代中遍历整个单词列表
word\u list1
,对于较大的单词列表,这可能会变得非常缓慢。
words_to_replace = [...]
word_list1 = ["cccc", "bbbb", "aaa"]
string = 'String'
for word in words_to_replace:
   new_string = string.replace(word, words_list1[0])
   string = new_string