首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用luigi处理unicode

用luigi处理unicode
EN

Stack Overflow用户
提问于 2015-09-07 19:19:45
回答 1查看 1.1K关注 0票数 1

我有几个文本文件是用UTF-8编码的。我正在用luigi构建数据流,我想要的是一个接一个地将文件读入unicode字符串,清理它们,最后将它们写入一些新的UTF-8文件中。问题是,在run类的CleanText方法中,我似乎无法在luigi.LocalTarget中使用unicode。任何想法都将不胜感激!

顺便提一下,我需要使用unicode,以便以标准化的方式处理重音字符。这是我的代码:

代码语言:javascript
复制
import luigi
import os
import re

class InputText(luigi.ExternalTask):
    """
    Checks which inputs exist
    """
    filename = luigi.Parameter()

    def output(self):
        """
        Outputs a single LocalTarget
        """

        # The directory containing this file
        root = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + "/"
        return luigi.LocalTarget(root + self.filename)

class CleanText(luigi.Task):
    """docstring for CleanText"""
    input_dir = luigi.Parameter()
    clean_dir = luigi.Parameter()

    def requires(self):
        return [ InputText(self.input_dir + '/' + filename)
                for filename in os.listdir(self.input_dir) ]    

    def run(self):
        for inp, outp in zip(self.input(), self.output()):
            fi = inp.open('r')
            fo = outp.open('w')
            txt = fi.read().lower()#.decode('utf-8') ### <-- This doesnt work
            #txt = unicode(txt, 'utf-8') ### <-- This doesnt work either
            txt = self.clean_text(txt)
            print txt.decode('utf-8')[:100]
            print txt[:100]
            fo.write(txt.encode('utf-8'))
            fi.close()
            fo.close()

    def output(self):
        # return luigi.LocalTarget(self.clean_dir + '/' + 'prueba.txt')
        return [ luigi.LocalTarget(self.clean_dir + '/' + filename)
                for filename in os.listdir(self.input_dir) ]

    def clean_text(self, d):
        '''d debe ser un string en unicode'''
        d = re.sub(u'[^a-z0-9áéíóúñäëïöü]', ' ', d)
        d = re.sub(' +', ' ', d)
        d = re.sub(' ([^ ]{1,3} )+', ' ', d, )
        d = re.sub(' [^ ]*(.)\\1{2,}[^ ]* ', ' ', d)
        return d
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-25 14:10:31

我也有类似的问题要写,然后用luigi读取unicode文件。

我在Github https://github.com/spotify/luigi/issues/790上发现了这个关于MixedUnicodeBytesFormatluigi.format模块。阅读源代码,我得到了一个UTF8格式。可以将format参数传递给Target实例。

代码语言:javascript
复制
import luigi
from luigi.format import UTF8

luigi.LocalTarget('/path/to/data.csv', format=UTF8)

这可以在def output(self)方法中发生,因为它是一个Target。我认为您也可以在特定的格式中使用luigi.file.LocalFileSystem

希望这能有所帮助。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32444879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档