【问题标题】:How to get the Scala equivalent code for the Python code如何获取 Python 代码的 Scala 等效代码
【发布时间】:2021-11-17 03:44:02
【问题描述】:

有人可以帮助以下 Python 代码的 scala 等效项。 此代码用于递归列出 Databricks 中 Azure 存储中嵌套文件夹中的所有文件。

def deep_ls(path: str):
    
    for x in dbutils.fs.ls(path):
        if x.path[-1] is not '/':
            yield x
        else:
            for y in deep_ls(x.path):
                yield y
                 

from pprint import pprint
files = list(deep_ls("srcpath/2021/06/16/"))
for x in files:
  df = x.name
  pprint(df)

谢谢。

我试过的代码:

def deep_ls(path: String) = {
   
    for (x <-  dbutils.fs.ls(path)){
        if (x.path(-1) != '/') {
            return x
        }
          else{
            for (y <- deep_ls(x.path)){
                return y
            }
          }
    }
}

错误信息。

command-3888229438512929:5: error: method deep_ls has return statement; needs result type
                return x
                ^
    command-3888229438512929:8: error: recursive method deep_ls needs result type
                for (y <- deep_ls(x.path)){
                          ^

在给出函数的返回类型后,我收到以下错误。

command-3888229438512929:6: error: type mismatch;
 found   : com.databricks.backend.daemon.dbutils.FileInfo
 required: String
            return x
                   ^
command-3888229438512929:10: error: type mismatch;
 found   : Char
 required: String
                return y
                       ^
command-3888229438512929:4: error: type mismatch;
 found   : Unit
 required: String
    for (x <-  dbutils.fs.ls(path)){

【问题讨论】:

  • 我认为this answer 中的第一个代码块可以提供帮助。
  • @jwvh 我已经用代码编辑了帖子。请协助。
  • 错误不是很清楚吗?您需要为您的函数声明一个返回类型。而已。 : String.
  • 不要在 Scala 中使用return,它不会像你想的那样!
  • 还有什么你不理解的错误?需要添加方法的返回类型

标签: python scala apache-spark


【解决方案1】:

似乎您并不真正需要 Python 代码的惰性(生成器的东西)。因此等效的 Scala 代码是这样的:

def deep_ls(path: String): Seq[String] = {   
  dbutils.fs.ls(path).flatMap { x => 
    if (x.path(-1) != '/') {
      Seq(x)
    } else {
      deep_ls(x.path))
    }
  }
}

【讨论】:

  • J 感谢您的回复,我在 databricks 中使用此代码并收到以下错误。错误:类型不匹配;发现:需要 Seq[Object]:Seq[String] --- dbutils.fs.ls(path).flatMap { x =>
  • J 。请让我知道这是否适合您。
  • 我假设dbutils.fs.ls 的返回类型在我的回答中是String 的列表,但可能需要注意。你可以做相应的调整。
  • 它的包装数组。 [FileInfo(path='dbfs:srcpath/2021/06/16/0/CTMEZZ_670006375380_MOV_1_8_HD.xml', name='CTMEZZ_670006375380_MOV_1_8_HD.xml', size=6023),
猜你喜欢
  • 2014-01-29
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2013-09-02
相关资源
最近更新 更多