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

2024-03-29 09:25:25 发布

您现在位置: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]


Tags: text文本defnp数组单词arraytemp
3条回答
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),它将被替换。但是,如果它不存在,replace函数将不起任何作用,因此也可以。因此,if条件是不必要的

您可以使用列表理解

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'

假设您有一个要替换为“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

相关问题 更多 >