我正在使用 spark-shell 和 pyspark 对一篇文章进行字数统计。 line.split("") 和 python split() 上的 scala flatmap 获得不同的字数(scala 有更多)。我在 scala 代码中尝试了 split("+") 和 split("\W+") ,但无法将计数降到与 python 相同。
有谁知道什么模式会与 python 完全匹配?
最佳答案
Python 的 str.split()
默认分隔符有一些特殊的行为:
runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a
None
separator returns[]
.For example,
' 1 2 3 '.split()
returns['1', '2', '3']
在 Scala 中完全匹配 this 的最简单方法可能是这样的:
scala> """\S+""".r.findAllIn(" 1 2 3 ").toList
res0: List[String] = List(1, 2, 3)
scala> """\S+""".r.findAllIn(" ").toList
res1: List[String] = List()
scala> """\S+""".r.findAllIn("").toList
res2: List[String] = List()
另一种方法是预先trim()
字符串:
scala> " 1 2 3 ".trim().split("""\s+""")
res3: Array[String] = Array(1, 2, 3)
但这与 Python 对空字符串的行为不同:
scala> "".trim().split("""\s+""")
res4: Array[String] = Array("")
在 Scala 中,空字符串的 split()
返回一个包含一个元素的数组,但在 Python 中,结果是一个包含零的列表元素。
关于python - 如何让scala字符串拆分以匹配python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30008160/