python - 在 luigi 中处理 unicode

标签 python unicode luigi

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

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

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

最佳答案

我遇到了类似的问题,用 luigi 编写然后读取 unicode 文件。

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

import luigi
from luigi.format import UTF8

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

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

希望有帮助。

关于python - 在 luigi 中处理 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444879/

相关文章:

python - 使用 CSV 作为可变数据库?

python - MySQLdb/Python : Can't insert certain characters in the db

python - 如何正确配置 Luigi 任务重试?

python - 运行 Luigi 工作流程时没有可视化依赖图

python - 具有自定义颜色图的轮廓重复颜色而不是改变颜色

python - 函数/主机 key 是否可以在用 Python 编写的 Azure 函数中直接使用?

Python Selenium 页面无法保存源代码编码错误

python - 吐血: how to make a scrapy, python,以及Windows 7中可以处理unicode的postgres生态系统

python - 无法腌制 <class 'abc.class_name' > : attribute lookup class_name on abc failed

python - 如何使用pytest模拟类属性