Compare commits
21 Commits
a4e550797c
...
lib-devel
| Author | SHA1 | Date | |
|---|---|---|---|
| cf173843d2 | |||
| d8808ddf5b | |||
| b5ee32e924 | |||
| b69463a303 | |||
| 82710a73a3 | |||
| 275101eed3 | |||
| 3826c7d2d1 | |||
| 377251b59f | |||
| 428946e39a | |||
| c5662c8397 | |||
| e3307d8db5 | |||
| 01dd92e4da | |||
| 8628c3dbfb | |||
| d69a3d0628 | |||
| b6000c49fd | |||
| 851dcf103d | |||
| 4118ed82c3 | |||
| 435bb144ab | |||
| ccc06bc5f1 | |||
| ef91f8d26a | |||
| fe75d99736 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -3,3 +3,4 @@
|
||||
/.pydevproject
|
||||
/org.eclipse.core.resources.prefs
|
||||
bananaSPLIT/build
|
||||
/TestFiles/
|
||||
|
||||
13811
TestFiles/GUARDIAN 1993.txt
Normal file
13811
TestFiles/GUARDIAN 1993.txt
Normal file
File diff suppressed because it is too large
Load Diff
22792
TestFiles/NYT 1990.txt
Normal file
22792
TestFiles/NYT 1990.txt
Normal file
File diff suppressed because it is too large
Load Diff
23149
TestFiles/NYT 1994.txt
Normal file
23149
TestFiles/NYT 1994.txt
Normal file
File diff suppressed because it is too large
Load Diff
30024
TestFiles/NYT 1997.txt
Normal file
30024
TestFiles/NYT 1997.txt
Normal file
File diff suppressed because it is too large
Load Diff
1
bananaSPLIT/.gitignore
vendored
1
bananaSPLIT/.gitignore
vendored
@@ -1 +1,2 @@
|
||||
*.py[ocd]
|
||||
/bananaSPLIT.exe.spec
|
||||
|
||||
@@ -3,7 +3,6 @@ Created on 2 nov 2019
|
||||
|
||||
@author: Emanuele Trabattoni
|
||||
'''
|
||||
from libbabanasplit.libfancylogger import fancyLogger
|
||||
import json,os,glob,copy
|
||||
|
||||
class bananaCONF(object):
|
||||
@@ -11,7 +10,7 @@ class bananaCONF(object):
|
||||
Carica e Salva file di configurazione per bananaSPLITTER
|
||||
'''
|
||||
def __init__(self, workdir=None, logger=None):
|
||||
self.log = logger
|
||||
self.log = logger
|
||||
self.fileList = None
|
||||
self.workdir = None
|
||||
self.inUse = None
|
||||
@@ -26,7 +25,7 @@ class bananaCONF(object):
|
||||
|
||||
def open(self):
|
||||
self.log.info("Carico i file di configurazione")
|
||||
self.fileList = glob.glob(self.workdir+"\\*.json")
|
||||
self.fileList = glob.glob(r"*.json")
|
||||
if len(self.fileList) > 0:
|
||||
for f in self.fileList:
|
||||
try:
|
||||
@@ -65,8 +64,8 @@ class bananaCONF(object):
|
||||
f=open(self.inUse)
|
||||
json.dump(self.settingsList[self.inUse], f)
|
||||
f.close()
|
||||
except IOError as eee:
|
||||
self.log.error("Impossibile salvare il file: {}".format(self.inUse))
|
||||
except IOError as e:
|
||||
self.log.error("Impossibile salvare il file: {} - [{}]".format(self.inUse,e))
|
||||
pass
|
||||
|
||||
def getFiles(self):
|
||||
@@ -80,9 +79,5 @@ class bananaCONF(object):
|
||||
self.settingsList[self.inUse][k]=dict(v)
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
logg = fancyLogger()
|
||||
confloader = bananaCONF(workdir=".", logger=logg)
|
||||
confloader.open()
|
||||
|
||||
|
||||
@@ -3,17 +3,17 @@ Created on 2 nov 2019
|
||||
|
||||
@author: Emanuele Trabattoni
|
||||
'''
|
||||
import sys
|
||||
import sys, os
|
||||
import json
|
||||
import logging
|
||||
import colorama
|
||||
|
||||
class fancyLogger(object):
|
||||
'''
|
||||
Colorizza il logger di python, per un' esperienza alla willy wonka
|
||||
Colorizza il logger di python, per un' esperienza stile willy wonka
|
||||
'''
|
||||
def __init__(self, name="Logger", consoleLog=True, fileLog=True):
|
||||
settings = json.load(open("./testSettings.json"))["logger"]
|
||||
settings = json.load(open(os.getcwd()+r"\libbananasplit\testEN.json"))["logger"]
|
||||
colorama.init(convert=True)
|
||||
self.LRED = colorama.Fore.LIGHTRED_EX
|
||||
self.RED = colorama.Fore.RED
|
||||
@@ -83,7 +83,3 @@ class fancyLogger(object):
|
||||
self.critical("Test Critical")
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
l=fancyLogger(name="testLogger")
|
||||
l.testColors()
|
||||
pass
|
||||
@@ -3,12 +3,12 @@ Created on 2 nov 2019
|
||||
|
||||
@author: Emanuele Trabattoni
|
||||
'''
|
||||
from libbabanasplit.libfancylogger import fancyLogger
|
||||
import threading, time, parse, re, copy, slugify, os
|
||||
from slugify.slugify import slugify
|
||||
import time, parse, re, copy, os, threading
|
||||
|
||||
class bananaSPLITTER(threading.Thread):
|
||||
|
||||
def __init__(self, fileParams=None, logger=None):
|
||||
threading.Thread.__init__(self)
|
||||
self.fileParams = fileParams
|
||||
self.log = logger
|
||||
self.rawFile = None
|
||||
@@ -22,6 +22,7 @@ class bananaSPLITTER(threading.Thread):
|
||||
self.docStruct = self.fileParams['docStruct']
|
||||
self.settings = self.fileParams['settings']
|
||||
self.fileName = self.fileParams['name']
|
||||
self.outPath = self.paths['OUTworkPath']+slugify(self.fileName)
|
||||
self.beginTime = time.time()
|
||||
pass
|
||||
else:
|
||||
@@ -30,32 +31,57 @@ class bananaSPLITTER(threading.Thread):
|
||||
|
||||
def run(self):
|
||||
self.log.info("Nuovo SPLITTER su file: {}".format(self.fileName))
|
||||
self.openFile()
|
||||
self.remEmptyLines()
|
||||
self.splitFile()
|
||||
if self.settings['removeDuplicates']:
|
||||
self.log.info("Controllo se ci sono dei duplicati..")
|
||||
self.removeDuplicates()
|
||||
else:
|
||||
for idx, ff in enumerate(self.fileList):
|
||||
ff['duplicate']=False
|
||||
self.fileList[idx]=ff
|
||||
print('Salto il controllo dei duplicati..')
|
||||
if self.settings['saveSeparateFiles']:
|
||||
self.saveSeparate()
|
||||
if self.settings['saveBodyFile']:
|
||||
self.saveBody()
|
||||
try:
|
||||
self.openFile()
|
||||
self.remEmptyLines()
|
||||
self.splitFile()
|
||||
|
||||
if self.settings['removeDuplicates']:
|
||||
self.log.info("Controllo se ci sono dei duplicati..")
|
||||
self.removeDuplicates()
|
||||
else:
|
||||
for idx, ff in enumerate(self.fileList):
|
||||
ff['duplicate']=False
|
||||
self.fileList[idx]=ff
|
||||
self.log.warn('Salto il controllo dei duplicati..')
|
||||
# se il parse e la rimozione dei duplicati e' andata bene
|
||||
# preparo e inizio il salvataggio
|
||||
if os.path.exists(self.outPath):
|
||||
if self.settings['removeOldFiles']:
|
||||
os.chdir(self.outPath)
|
||||
for f in os.listdir(self.outPath):
|
||||
os.remove(f)
|
||||
else:
|
||||
raise FileExistsError("Non posso sovrascrivere i vecchi file, eliminali manualmente!")
|
||||
else:
|
||||
os.mkdir(self.outPath)
|
||||
os.chdir(self.outPath)
|
||||
if self.settings['saveSeparateFiles']:
|
||||
self.saveSeparate()
|
||||
if self.settings['saveBodyFile']:
|
||||
self.saveBody()
|
||||
self.log.info("L'elaborazione del file ha richiesto {:4.2f} sec".format(time.time()-self.beginTime))
|
||||
|
||||
except UnicodeDecodeError as ee:
|
||||
self.log.critical("Il file [{}] contiene caratteri non compatibili con la codifica scelta! [{}]"
|
||||
.format(self.fileParams['name'],ee))
|
||||
except FileExistsError as fe:
|
||||
self.log.critical(fe)
|
||||
except BaseException as ee:
|
||||
self.log.warning(ee)
|
||||
pass
|
||||
|
||||
def openFile(self):
|
||||
try:
|
||||
self.info("Carico il contenuto..")
|
||||
os.chdir(self.paths["INworkPath"])
|
||||
self.log.info("Carico il contenuto..")
|
||||
fp = open(self.fileParams['name'], mode='r', encoding=self.settings['encoding'])
|
||||
self.rawFile = fp.readlines()
|
||||
fp.close()
|
||||
except IOError as e:
|
||||
self.log.critical("Impossibile aprire il file: {}! [{}]".format(self.fileName,e))
|
||||
raise BaseException("OpenFile")
|
||||
os.rmdir(self.outPath)
|
||||
pass
|
||||
|
||||
def remEmptyLines(self):
|
||||
@@ -76,9 +102,12 @@ class bananaSPLITTER(threading.Thread):
|
||||
|
||||
def splitFile(self): #porting del codice dal programma originale
|
||||
self.log.info("Individuo il contenuto..")
|
||||
self.bodyCounter=0
|
||||
self.duplicateNumber=0
|
||||
docNumber = 0
|
||||
docSkipped = 0
|
||||
docDate = {}
|
||||
title = ''
|
||||
prevLine = ''
|
||||
newsPaperName = ''
|
||||
titleBegin = False
|
||||
@@ -96,16 +125,16 @@ class bananaSPLITTER(threading.Thread):
|
||||
pass
|
||||
else:
|
||||
if self.settings["showSkipped"]:
|
||||
self.log.warning("Il conto dei documenti non torna! LexisNexis \
|
||||
self.log.warn("Il conto dei documenti non torna! LexisNexis \
|
||||
ne ha saltato qualcuno!\nPrecedente:{0}-Attuale:{1}".format(docNumber,nn["current"]))
|
||||
docSkipped+=1
|
||||
docNumber = nn["current"]
|
||||
except:
|
||||
pass #non segnalare eccezione se il parse fallisce
|
||||
# ricerco la data
|
||||
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docParams['dateWords']:
|
||||
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['dateWords']:
|
||||
try:
|
||||
docDate=parse.parse(self.docParams['dateFormat'],l).named
|
||||
docDate=parse.parse(self.docStruct['dateFormat'],l).named
|
||||
docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
|
||||
docDate['month']=self.docStruct['dateWords'].index(docDate['month'])+1
|
||||
title = ''
|
||||
@@ -118,12 +147,12 @@ class bananaSPLITTER(threading.Thread):
|
||||
else:
|
||||
newsPaperName = self.settings['nameNotFoundStr']
|
||||
except:
|
||||
self.log.warning("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\
|
||||
controlla i file di uscita! \n\t[{}]".format(prevLine.strip()))
|
||||
self.log.warn("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\
|
||||
controlla i file di uscita! [{}]".format(prevLine.strip()))
|
||||
else:
|
||||
newsPaperName = self.settings['nameNotFoundStr']
|
||||
except:
|
||||
self.log.warning("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: \n\t[{}]". format(l.strip('\r\n')))
|
||||
self.log.warn("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]". format(l.strip('\r\n')))
|
||||
pass
|
||||
elif lineWords[0] in self.docStruct['headWords']:
|
||||
#cambio stato e inizializzo un nuovo documento da riempire
|
||||
@@ -155,7 +184,7 @@ class bananaSPLITTER(threading.Thread):
|
||||
self.status = 'tail'
|
||||
anomaly = False
|
||||
if docSep.match(l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali
|
||||
self.log.warning("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\
|
||||
self.log.warn("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\
|
||||
L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t[{}]".format(docNumber, l.strip()))
|
||||
self.status = 'tail'
|
||||
anomaly = True
|
||||
@@ -178,7 +207,7 @@ class bananaSPLITTER(threading.Thread):
|
||||
#ricerca terminata, espongo i risultati
|
||||
self.log.info("Nel file ho trovato {0} articoli..".format(self.bodyCounter))
|
||||
if docSkipped > 0:
|
||||
self.log.warning("Attentione, LexisNexis ne ha saltati {} !!!".format(docSkipped))
|
||||
self.log.warn("Attentione, LexisNexis ne ha saltati {} !!!".format(docSkipped))
|
||||
pass
|
||||
pass
|
||||
|
||||
@@ -199,10 +228,12 @@ class bananaSPLITTER(threading.Thread):
|
||||
ff['duplicate'] = True
|
||||
self.fileList[idx]=ff
|
||||
self.duplicateNumber+=1
|
||||
self.log.info("Ho rimosso {} duplicati di {} articoli..\n". format(self.duplicateNumber, len(duplicateList)))
|
||||
self.log.info("Ho rimosso {} duplicati di {} articoli..". format(self.duplicateNumber, len(duplicateList)))
|
||||
pass
|
||||
|
||||
def saveSeparate(self):
|
||||
outFileCounter = 0
|
||||
self.paths['OUTworkPath']=self.paths['OUTworkPath']+slugify(self.fileName)
|
||||
self.log.info("Salvo gli articoli in file separati...")
|
||||
self.log.debug("Persorso: {0}".format(self.paths['OUTworkPath'].format('nomeFile')))
|
||||
for ff in self.fileList:
|
||||
@@ -210,37 +241,36 @@ class bananaSPLITTER(threading.Thread):
|
||||
if ff['duplicate'] == False:
|
||||
fName=self.paths['OUTnameFormat'].format(title=slugify(ff['title'][:self.settings['maxTitleLen']]),\
|
||||
filename=slugify(self.fileName),\
|
||||
docnum=self.bodyCounter,\
|
||||
docnum=outFileCounter,\
|
||||
papername=ff['newsPaperName'].strip(),\
|
||||
**ff['date'])
|
||||
out=open(self.paths['OUTworkPath']+'{0}'.format(fName),'wb')
|
||||
out=open('{0}'.format(fName),'wb')
|
||||
if self.settings['includeTitle']:
|
||||
ff['content'] = ff['title']+os.linesep+ff['content']
|
||||
out.write(ff['content'].encode(self.settings['encoding']))
|
||||
out.close()
|
||||
self.bodyCounter+=1
|
||||
outFileCounter+=1
|
||||
except IOError as e:
|
||||
self.log.error("Qualcosa e\' andato storto, non riesco a scrivere il file: {}".format(e))
|
||||
continue
|
||||
if outFileCounter < self.bodyCounter:
|
||||
raise BaseException("Ho salvato meno file rispetto a quelli trovati!")
|
||||
pass
|
||||
|
||||
def saveBody(self):
|
||||
print('Salvo gli articoli in un singolo file vicino agli originali...')
|
||||
print ('Persorso: {0}'.format(self.paths['OUTworkPath'].format('nomeFile')))
|
||||
self.log.info('Salvo gli articoli in un singolo file vicino agli originali...')
|
||||
self.log.debug('Persorso: {0}'.format(self.outPath))
|
||||
os.chdir(self.outPath)
|
||||
try:
|
||||
fName=slugify(self.fileName)
|
||||
fName='BODYFILE_{0}_{1}.txt'.format(self.fileCounter,fName[:self.settings['maxTitleLen']])
|
||||
fName='BODYFILE_{0}.txt'.format(fName[:self.settings['maxTitleLen']])
|
||||
fileContent = os.linesep.join([cc['content'] for cc in self.fileList])
|
||||
out=open(self.paths['OUTworkPath']+'{0}'.format(fName),'wb')
|
||||
out=open('{0}'.format(fName),'wb')
|
||||
out.write(fileContent.encode(self.settings['encoding']))
|
||||
out.close()
|
||||
except IOError as e:
|
||||
print("OOPS! Qualcosa e\' andato storto, non riesco a scrivere il file: {}".format(e))
|
||||
continue
|
||||
self.log.error("Qualcosa e\' andato storto, non riesco a scrivere il file: {}".format(e))
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
logg = fancyLogger(name="LibSplit")
|
||||
spp = bananaSPLITTER(fileParams="testfile.txt", logger=logg)
|
||||
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
"logTimeFormat": "%m-%d %H:%M:%S"
|
||||
},
|
||||
"splitter": {
|
||||
"name": "",
|
||||
"paths": {
|
||||
"INworkPath": "D:\\Test\\",
|
||||
"OUTworkPath": "D:\\Test\\Separati\\",
|
||||
"INworkPath": "D:\\Emanuele\\Documenti\\workspace\\bananaSPLIT\\TestFiles\\",
|
||||
"OUTworkPath": "H:\\",
|
||||
"OUTnameFormat": "TEST_{docnum}_{year:04d}{month:02d}{day:02d}_{title}.txt"
|
||||
},
|
||||
"docStruct": {
|
||||
@@ -57,8 +58,8 @@
|
||||
"nameNotFoundStr": "ND",
|
||||
"includeTitle": true,
|
||||
"removeDuplicates": true,
|
||||
"showSkipped": false,
|
||||
"showRemovedDuplicates": true,
|
||||
"showSkipped": true,
|
||||
"showRemovedDuplicates": false,
|
||||
"maxTitleLen": 32,
|
||||
"loadTXT": true,
|
||||
"loadDOCX": false,
|
||||
80
bananaSPLIT/libbananasplit/testITA.json
Normal file
80
bananaSPLIT/libbananasplit/testITA.json
Normal file
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"version": "v1.1a",
|
||||
"logger": {
|
||||
"logFile": "D:\\Test\\bananaSPLIT.log",
|
||||
"logFormat": "%(asctime)s|%(levelname)-8s| %(message)-50s",
|
||||
"logTimeFormat": "%m-%d %H:%M:%S"
|
||||
},
|
||||
"splitter": {
|
||||
"name": "",
|
||||
"paths": {
|
||||
"INworkPath": "D:\\Emanuele\\Documenti\\workspace\\bananaSPLIT\\TestFiles\\",
|
||||
"OUTworkPath": "H:\\",
|
||||
"OUTnameFormat": "TEST_{docnum}_{year:04d}{month:02d}{day:02d}_{title}.txt"
|
||||
},
|
||||
"docStruct": {
|
||||
"docSep": "Copyright [(0-9)]+",
|
||||
"dateFormat": "{day:d} {month} {year:d} {}",
|
||||
"dateWords": [
|
||||
"Gennaio",
|
||||
"Febbraio",
|
||||
"Marzo",
|
||||
"Aprile",
|
||||
"Maggio",
|
||||
"Giugno",
|
||||
"Luglio",
|
||||
"Agosto",
|
||||
"Settembre",
|
||||
"Ottobre",
|
||||
"Novembre",
|
||||
"Dicembre"
|
||||
],
|
||||
"headWords": [
|
||||
"BYLINE:",
|
||||
"SECTION:",
|
||||
"LENGTH:",
|
||||
"DATELINE:",
|
||||
"HIGHLIGHT:",
|
||||
"Email:"
|
||||
],
|
||||
"tailWords": [
|
||||
"LANGUAGE:",
|
||||
"GRAPHIC:",
|
||||
"TYPE:",
|
||||
"URL:",
|
||||
"LOAD-DATE:",
|
||||
"PUBLICATION-TYPE:",
|
||||
"DOCUMENT-TYPE:",
|
||||
"CHARTS:"
|
||||
]
|
||||
},
|
||||
"settings": {
|
||||
"encoding": "utf-8",
|
||||
"monthPosition": 0,
|
||||
"getNewsPaperName": true,
|
||||
"nameNotFoundStr": "ND",
|
||||
"includeTitle": true,
|
||||
"removeDuplicates": true,
|
||||
"showSkipped": false,
|
||||
"showRemovedDuplicates": true,
|
||||
"maxTitleLen": 32,
|
||||
"loadTXT": true,
|
||||
"loadDOCX": false,
|
||||
"removeOldFiles": true,
|
||||
"saveSeparateFiles": true,
|
||||
"saveBodyFile": true,
|
||||
"saveBodyNumber": true,
|
||||
"delLF": false,
|
||||
"delWordBreak": true,
|
||||
"delChars": [
|
||||
"'",
|
||||
"@",
|
||||
"#",
|
||||
"$",
|
||||
"%",
|
||||
"^",
|
||||
"&"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
35
bananaSPLIT/libtestmain.py
Normal file
35
bananaSPLIT/libtestmain.py
Normal file
@@ -0,0 +1,35 @@
|
||||
'''
|
||||
Created on 1 dic 2019
|
||||
|
||||
@author: Emanuele Trabattoni
|
||||
'''
|
||||
import os
|
||||
from glob import glob
|
||||
from copy import deepcopy
|
||||
from libsplit import bananaSPLITTER
|
||||
from libconfload import bananaCONF
|
||||
from libfancylogger import fancyLogger
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("CWD-> "+os.getcwd())
|
||||
logger = fancyLogger(fileLog = False)
|
||||
confl = bananaCONF(workdir=r"./libbananasplit", logger=logger)
|
||||
confl.open()
|
||||
|
||||
confl.use("testEN.json")
|
||||
splconf = confl.getParams("splitter")
|
||||
splist = []
|
||||
os.chdir(splconf["paths"]["INworkPath"])
|
||||
for f in glob("*.txt"):
|
||||
splconf["name"] = f
|
||||
logger.info("-"*80)
|
||||
splitter = bananaSPLITTER(fileParams=deepcopy(splconf), logger=logger)
|
||||
splist.append(splitter)
|
||||
splitter.start()
|
||||
splitter.join()
|
||||
|
||||
logger.info("\n"+"="*50+"\n\tFINITO!!!\n"+"="*50)
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user