Scala 替换/删除单独列表中存在的字符串中的单词
我正在寻找一种更好、更干净的方法来清除长字符串中的坏单词 我有一个包含数百个坏单词的文本文件,我正在对每个坏单词进行循环-使用它创建一个正则表达式模式,并用星号替换匹配项Scala 替换/删除单独列表中存在的字符串中的单词,scala,replace,Scala,Replace,我正在寻找一种更好、更干净的方法来清除长字符串中的坏单词 我有一个包含数百个坏单词的文本文件,我正在对每个坏单词进行循环-使用它创建一个正则表达式模式,并用星号替换匹配项 导入scala.io.Source def removeBadWords(注释:字符串):字符串={ val bufferedbaddwords=Source.fromFile(“/Users/me/Desktop/baddwords.txt”) val baddwords=bufferedbaddwords.getLines
导入scala.io.Source
def removeBadWords(注释:字符串):字符串={
val bufferedbaddwords=Source.fromFile(“/Users/me/Desktop/baddwords.txt”)
val baddwords=bufferedbaddwords.getLines.toList
bufferedBadWords.close
var newComment=注释
对于(badWord您可以在一次传递中完成所有操作,但是您可能无法让替换字符串与坏字符串的长度匹配
def removeBadWords(comment :String) :String =
io.Source
.fromFile("badwords.txt") //open file
.getLines //without newline chars
.mkString("\\b(", "|", ")\\b") //regex with word boundaries
.r //compile
.replaceAllIn(comment, "****") //return cleaned comment