【问题标题】:Escape comma while reading using sc.textFile (APACHE SPARK RDD) [duplicate]使用 sc.textFile(APACHE SPARK RDD)阅读时转​​义逗号 [重复]
【发布时间】:2016-09-10 09:37:34
【问题描述】:

我正在尝试使用 python 将 csv 读取到 rdd(SPARK)。我遇到的问题是使用逗号作为分隔符的拆分函数。只要每列中没有逗号,它就可以正常工作。如果有逗号,逗号将每一列分成多列。

例如

empid、emp 职称、emp desc、大学 123、开发者,开发者的角色是用C、C++等语言开发软件,学院1

data = sc.textfile("files.csv")
empid, emp title, emp desc, college = line.strip().split(",")

在上面的示例中,emp desc 也被拆分为大学,请告诉我在读取数据集时如何处理每列中的逗号?

【问题讨论】:

    标签: python apache-spark rdd


    【解决方案1】:

    实际上不可能知道哪些逗号应该是分隔符,哪些不是没有附加信息。您最好的选择可能是更改分隔符或确保所有非分隔符逗号在输入时以某种方式“转义”。

    使用转义的解决方案:

    如果所有非分隔符逗号都带有前缀,例如“\”,那么您可以用逗号分隔并加入任何以转义符开头的条目\

    line = '123, developer, the role of developer is to develop softwares using languages such as C\\, C++ etc, college1'
    
    temp = line.strip().split(',')
    
    i=0
    while i < len(temp)-1:
        if temp[i][-1] == '\\':
            temp[i:i+2] = [','.join(temp[i:i+2])]
        else:
            temp[i] = ','.join(temp[i].split('\\,'))
            i += 1
    
    empid, emp_title, emp_desc, college = temp
    print('empid: '+empid+'\nemp_title: '+emp_title+'\nemp_desc: '+emp_desc+'\ncollege: '+college)
    

    输出:

    empid: 123
    emp_title:  developer
    emp_desc:  the role of developer is to develop softwares using languages such as C, C++ etc
    college:  college1
    

    使用附加信息的解决方案:

    另一方面,如果您由于某种原因不能对非分隔符逗号使用转义符,那么您的下一个最佳选择是强加附加信息。例如,如果您有理由相信只有 emp_desc 变量将有非分隔符逗号,那么您总是可以这样做:

    temp = line.strip().split(",")
    empid = temp[0]
    emp_title = temp[1]
    emp_desc = temp[2:len(temp)-1]
    college = temp[-1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      相关资源
      最近更新 更多