烫伤后我需要:
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)发布于 2014-07-15 16:30:58
编辑距离可以按照维基百科中的描述进行计算。
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))
https://stackoverflow.com/questions/24758112
复制相似问题