如何分割scala字符串以匹配python

2024-09-28 23:44:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用sparkshell和pyspark对一篇文章进行字数统计。scala地图线.分割(“”)和python split()得到不同的字数(scala有更多)。我在scala代码中尝试了split(“+”)和split(“\W+”),但无法使计数降到与python相同的数量。在

有人知道什么样的模式能与python完全匹配吗?在


Tags: 代码数量文章地图模式pyspark计数split
1条回答
网友
1楼 · 发布于 2024-09-28 23:44:28

Python的^{}对于默认分隔符有一些特殊的行为:

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中完全匹配的最简单方法可能如下:

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()字符串:

^{pr2}$

但这与Python对于空字符串的行为不同:

scala> "".trim().split("""\s+""")
res4: Array[String] = Array("")

在Scala中,空字符串的split()返回一个包含one元素的数组,但在Python中,结果是一个包含元素的列表。在

相关问题 更多 >