使用缩放功能,我需要:
edit-distance
指标(http://en.wikipedia.org/wiki/Edit_distance)string; string; distance
的CSV文件要对字符串进行分组,请使用
map
和groupBy
,如以下示例所示:import cascading.tuple.Fields
import com.twitter.scalding._
class Scan(args: Args) extends Job(args) {
val output = TextLine("tmp/out.txt")
val wordsList = List(
("aaaa"),
("aaabb"),
("aabbcc"),
("aaabccdd"),
("aaabbccdde"),
("aaabbddd"),
("bbbb"),
("bbbaaa"),
("bbaaabb"),
("bbbcccc"),
("bbbddde"),
("ccccc"),
("cccaaa"),
("ccccaabbb"),
("ccbbbddd"),
("cdddeee")
)
val orderedPipe =
IterableSource[(String)](wordsList, ('word))
.map('word -> 'key ){word:String => word.take(3)}
.groupBy('key) {_.toList[String]('word -> 'x) }
.debug
.write(output)
}
结果,我得到:
['aaa', 'List(aaabbddd, aaabbccdde, aaabccdd, aaabb, aaaa)']
['aab', 'List(aabbcc)']
['bba', 'List(bbaaabb)']
['bbb', 'List(bbbddde, bbbcccc, bbbaaa, bbbb)']
['ccb', 'List(ccbbbddd)']
['ccc', 'List(ccccaabbb, cccaaa, ccccc)']
['cdd', 'List(cdddeee)']
现在,在此示例中,我需要使用此列表中的
aaa
键来计算字符串的编辑距离:List(aaabbddd, aaabbccdde, aaabccdd, aaabb, aaaa)
接下来是此列表中所有带有'bbb'键的字符串的内容:
List(bbbddde, bbbcccc, bbbaaa, bbbb)
等等
要计算每个组中所有字符串之间的编辑距离,我需要用自己的函数替换
toList
,我该怎么做?还有如何将函数的结果写入CSV文件?谢谢!
更新
如何从扩展
List
获取Pipe
?toList
只是返回另一个Pipe
,所以我不能全部使用它: val orderedPipe =
IterableSource[(String)](wordsList, ('word))
.map('word -> 'key ){word:String => word.take(3)}
.groupBy('key) {_.toList[String]('word -> 'x) }
.combinations(2) //---ERROR! Pipe has no such method!
.debug
.write(output)
最佳答案
可以按照wikipedia中的描述来计算编辑距离:
def editDistance(a: String, b: String): Int = {
import scala.math.min
def min3(x: Int, y: Int, z: Int) = min(min(x, y), z)
val (m, n) = (a.length, b.length)
val matrix = Array.fill(m + 1, n + 1)(0)
for (i <- 0 to m; j <- 0 to n) {
matrix(i)(j) = if (i == 0) j
else if (j == 0) i
else if (a(i-1) == b(j-1)) matrix(i-1)(j-1)
else min3(
matrix(i - 1)(j) + 1,
matrix(i)(j-1) + 1,
matrix(i - 1)(j - 1) + 1)
}
matrix(m)(n)
}
为了找到列表元素的成对编辑距离:
def editDistances(list: List[String]) = {
list.combinations(2).toList.map(x => (x(0), x(1), editDistance(x(0), x(1))))
}
在groupBy中使用它:
val orderedPipe =
IterableSource[(String)](wordsList, ('word))
.map('word -> 'key ){word:String => word.take(3)}
.groupBy('key) {_.mapList[String, List[(String, String, Int)]]('word -> 'x)(editDistances)}
.debug
.write(output)
就写入csv格式而言,您可以简单地使用
com.twitter.scalding.Csv
类。write(Csv(outputFile))