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