nlp/spacy_nlp

84 lines
2.7 KiB
Plaintext
Raw Normal View History

2019-05-23 08:09:01 +00:00
#!/usr/bin/env python3.5
2019-02-06 15:58:17 +00:00
# coding=utf-8
2020-02-04 12:12:31 +00:00
from xml.sax.saxutils import escape
2019-02-06 15:58:17 +00:00
import argparse
2020-02-12 13:16:36 +00:00
import chardet
2019-02-06 15:58:17 +00:00
import spacy
import textwrap
2019-02-06 15:58:17 +00:00
2019-05-20 09:28:51 +00:00
parser = argparse.ArgumentParser(
2019-09-11 14:15:41 +00:00
description=('Tag a text file with spaCy and save it as a verticalized '
'text file.')
2019-05-20 09:28:51 +00:00
)
2019-09-11 14:15:41 +00:00
parser.add_argument('i', metavar='txt-sourcefile')
parser.add_argument('-l',
choices=['de', 'el', 'en', 'es', 'fr', 'it', 'nl', 'pt'],
dest='lang',
required=True)
parser.add_argument('o', metavar='vrt-destfile')
parser.add_argument('--check-encoding',
default=False,
action='store_true',
dest='check_encoding'
)
2019-02-06 15:58:17 +00:00
args = parser.parse_args()
2019-09-11 14:15:41 +00:00
SPACY_MODELS = {'de': 'de_core_news_sm',
'el': 'el_core_news_sm',
'en': 'en_core_web_sm',
'es': 'es_core_news_sm',
'fr': 'fr_core_news_sm',
'it': 'it_core_news_sm',
'nl': 'nl_core_news_sm',
'pt': 'pt_core_news_sm'}
2019-02-06 15:58:17 +00:00
# Set the language model for spacy
nlp = spacy.load(SPACY_MODELS[args.lang])
# Try to determine the encoding of the text in the input file
if args.check_encoding:
with open(args.i, "rb") as input_file:
bytes = input_file.read()
encoding = chardet.detect(bytes)['encoding']
else:
2020-02-12 13:25:08 +00:00
encoding = 'utf-8'
# Read text from the input file and if neccessary split it into parts with a
# length of less than 1 million characters.
with open(args.i, encoding=encoding) as input_file:
2019-02-06 15:58:17 +00:00
text = input_file.read()
texts = textwrap.wrap(text, 1000000, break_long_words=False)
2019-03-06 13:55:52 +00:00
text = None
2019-02-06 15:58:17 +00:00
# Create and open the output file
2019-05-20 09:28:51 +00:00
output_file = open(args.o, 'w+')
output_file.write('<?xml version="1.0" encoding="UTF-8"?>\n'
'<corpus>\n'
'<text>\n')
for text in texts:
# Run spacy nlp over the text (partial string if above 1 million chars)
doc = nlp(text)
for sent in doc.sents:
output_file.write('<s>\n')
for token in sent:
# Skip whitespace tokens like "\n" or "\t"
if token.text.isspace():
continue
# Write all information in .vrt style to the output file
# text, lemma, simple_pos, pos, ner
2019-05-20 09:28:51 +00:00
output_file.write(
2019-09-11 14:15:41 +00:00
'{}\t{}\t{}\t{}\t{}\n'.format(
2020-02-04 12:12:31 +00:00
escape(token.text),
escape(token.lemma_),
2019-09-11 14:15:41 +00:00
token.pos_,
token.tag_,
token.ent_type_ if token.ent_type_ != '' else 'NULL'
)
2019-05-20 09:28:51 +00:00
)
output_file.write('</s>\n')
output_file.write('</text>\n'
'</corpus>')
2019-05-20 09:28:51 +00:00
2019-03-05 14:01:57 +00:00
output_file.close()