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

How to replace word in array of text in Python?

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

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

def stem_text(text):
     text = text.split()
     array = np.array(text)
     temp = np.where(array == word_list1, word_list1[0], array)
     text = ' '.join(temp)
     return text

我想这样做:

对于 word_list1 中的所有单词,检查文本,如果某些单词匹配,将其替换为 word_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'
word_list1 = ["cccc", "bbbb", "aaa"]

def stem_text(text):
  text = text.split()

  for keyword in word_list1:
    text.replace(keyword, word_list1[0])

  text = ' '.join(temp)
  return text

您可以 运行 对其进行替换。如果它存在 (if keyword in text),它将被替换。但如果它不存在,替换函数将不执行任何操作,所以这也很好。所以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