Pig的utf8编码

w41d8nur  于 2021-06-25  发布在  Pig
关注(0)|答案(2)|浏览(315)

加载包含某些特定字符的数据(例如,à, ° 使用pig拉丁语并将数据存储在.txt文件中,可以看到txt文件中的这些符号显示为� 以及ï 角色。这是因为utf-8替换字符。我想问的是,是否有可能以某种方式避免它,例如使用一些pig命令,在结果中(在txt文件中)à 而不是�?

nkkqxpd9

nkkqxpd91#

你是对的这是因为文字(http://hadoop.apache.org/docs/r2.6.0/api/org/apache/hadoop/io/text.html)自动将传入数据(字节)转换为utf-8。为了避免这种情况,您不应该使用文本。
也就是说,应该使用bytearray类型而不是chararray(bytearray不使用文本,因此不进行转换)。由于您没有指定任何代码,因此我将提供一个示例进行说明:
你(可能)就是这么做的:

converted_to_utf = LOAD 'strangeEncodingdata' using TextLoader AS (line:chararray);

这就是你想做的:

no_conversion = LOAD 'strangeEncodingdata' using TextLoader AS (line:bytearray);
3bygqnnd

3bygqnnd2#

在pig中,我们内置了动态调用程序,允许pig程序员引用java函数,而不必将它们 Package 在自定义pig udf中。所以现在你可以把数据作为utf-8编码的字符串加载,然后解码,然后对它执行所有操作,然后把它存储回utf-8。我想这应该适用于第一部分:

DEFINE UrlDecode InvokeForString('java.net.URLDecoder.decode', 'String String');
    encoded_strings = LOAD 'encoded_strings.txt' as (encoded:chararray);
    decoded_strings = FOREACH encoded_strings GENERATE UrlDecode(encoded, 'UTF-8');

负责执行此操作的java代码是:

import java.io.IOException;
    import java.net.URLDecoder;

    import org.apache.pig.EvalFunc;
    import org.apache.pig.data.Tuple;

    public class UrlDecode extends EvalFunc<String> {

        @Override
        public String exec(Tuple input) throws IOException {
            String encoded = (String) input.get(0);
            String encoding = (String) input.get(1);
            return URLDecoder.decode(encoded, encoding);
        }
    }

现在修改此代码以从普通字符串返回utf-8编码的字符串,并将其存储到文本文件中。希望有用。

相关问题