我想使用自己的数组来阻止文本:
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
),它将替换。但是,如果它不存在,那么replace函数将什么也不做,所以也很好。因此,if条件不是必需的。
假设您有一个要用“ cccc”替换的单词列表和一个要查找并替换它们的字符串。
words_to_replace = [...]
word_list1 = ["cccc", "bbbb", "aaa"]
string = 'String'
for word in words_to_replace:
new_string = string.replace(word, words1[0])
string = new_string