在路易吉处理unicode

时间:2015-09-07 19:19:45

标签: python unicode luigi

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

正如旁注,我需要使用unicode以标准化的方式处理重音字符。这是我的代码:

window.onload = function () {
    // regex for finding "loaded" query string parameter
    var qsRegex = /^(\?|.+&)loaded=\d/ig;
    if (!qsRegex.test(location.search)) {
        var loc = window.location.href + (window.location.search.length ? '&' : '?') + 'loaded=1';
        window.history.replaceState(null, document.title, loc);
    }
};

1 个答案:

答案 0 :(得分:1)

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

我在Github https://github.com/spotify/luigi/issues/790上发现了MixedUnicodeBytesFormat模块中的luigi.format。阅读源代码,我有一个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特定的格式。

希望有所帮助。