【问题标题】:PySpark DF and RDD encoding of latin letters拉丁字母的 PySpark DF 和 RDD 编码
【发布时间】:2018-07-03 10:06:38
【问题描述】:

我必须在Spark 中导入CSV 文件并将其转换为DF,然后在处理之前将其转换为RDD

首先我将完整的CSV 文件导入为DF

stopwords_df = (
    sqlc
    .read
    .format('csv')
    .option('header', True)
    .option('delimiter', ';')
    .option('encoding', 'latin1')
    .load('/mnt/sparkdata/stopwords.csv', schema = stopSchema)
    .repartition(72)
)

然后我只选择合适的单词并将其转换为一个集合

stopwords_set = set(
    stopwords_df
    .filter(f.col('retain').isNull())
    .rdd
    .map(lambda x: x[0].encode('latin1')) # the [0] is to extract strings from Rows
    .collect()
)

我搞砸了编码,我不知道如何解决这个问题。

如果我“显示”DF,拉丁字母将正确显示 (sperò)

stopwords_df.show(100, truncate = False)

+--------------+--------+------+----------+------+
|word          |language|type  |doubletype|retain|
+--------------+--------+------+----------+------+
|informava     |IT      |verbo |null      |null  |
|sperò         |IT      |verbo |null      |null  |
|four          |EN      |null  |null      |null  |

但是如果我显示 RDD 就不会发生这种情况

(
    stopwords_df
    .filter(f.col('word') == r'sperò')
    .rdd
    .first()
)

Row(word=u'sper\xf2', language=u'IT', type=u'verbo', doubletype=None, retain=None)

UTF-8 encoding 也会变得更糟

+--------------+--------+------+----------+------+
|word          |language|type  |doubletype|retain|
+--------------+--------+------+----------+------+
|thanks        |EN      |saluto|null      |null  |
|fossero       |IT      |verbo |null      |null  |
|sper�         |IT      |verbo |null      |null  |

你能建议我如何解决这个问题吗?

【问题讨论】:

    标签: python apache-spark encoding character-encoding pyspark


    【解决方案1】:

    看到这一行后:

    Row(word=u'sper\xf2)
    

    这确实暗示您使用的是 Python 3。Python 3 的默认编码是 utf-8,并且默认支持 ò。

    因此,当您指定将其编码为 latin1 时,ò 将替换为 \xf2。

    为什么不收集没有latin1的编码?

    stopwords_set = set(
        stopwords_df
        .filter(f.col('retain').isNull())
        .rdd
        .collect()
    )
    

    如果这有帮助,请告诉我。 谢谢。

    【讨论】:

    • 感谢您的编辑。我从手机上回答了这个问题,因此无法格式化。感谢您的耐心等待。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2013-08-28
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多