本文整理汇总了Python中spacy.io方法的典型用法代码示例。如果您正苦于以下问题:Python spacy.io方法的具体用法?Python spacy.io怎么用?Python spacy.io使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类spacy
的用法示例。
在下文中一共展示了spacy.io方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ensure_proper_language_model
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def ensure_proper_language_model(nlp: Optional['Language']) -> None:
"""Checks if the spacy language model is properly loaded.
Raises an exception if the model is invalid."""
if nlp is None:
raise Exception("Failed to load spacy language model. "
"Loading the model returned 'None'.")
if nlp.path is None:
# Spacy sets the path to `None` if
# it did not load the model from disk.
# In this case `nlp` is an unusable stub.
raise Exception("Failed to load spacy language model for "
"lang '{}'. Make sure you have downloaded the "
"correct model (https://spacy.io/docs/usage/)."
"".format(nlp.lang))
示例2: com_annotations
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def com_annotations(data_type: str, rp: str):
"""
This method computes all the annotations, Lemma, POS, IS_STOPWORD etc., in the form of spaCy doc container
for all the rows (lines) in the text data and saves the object of list of the doc (container) for each line.
# doc = spaCy container - [https://spacy.io/api/doc]
:argument:
:param data_type: String either `training` or `test`
:param rp: Absolute path of the root directory of the project
:return:
boolean_flag: True for successful operation.
all_annotations: List of doc (spaCy containers) of all the lines in the data.
"""
nlp = spacy.load("en_core_web_lg")
all_annotations = []
read_flag, file = read_file("raw_sentence_{0}".format(data_type), rp)
if read_flag:
for line in file:
doc = nlp(remove_endline_char(line))
all_annotations.append(doc)
file.close()
return True, all_annotations
else:
return False
示例3: __init__
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def __init__(self,model='en'):
"""
Create a Parser object that will use Spacy for parsing. It offers all the same languages that Spacy offers. Check out: https://spacy.io/usage/models. Note that the language model needs to be downloaded first (e.g. python -m spacy download en)
:param model: Name of an available Spacy language model for parsing (e.g. en/de/es/pt/fr/it/nl)
:type model: str
"""
# We only load spacy if a Parser is created (to allow ReadTheDocs to build the documentation easily)
import spacy
self.model = model
if not model in Parser._models:
Parser._models[model] = spacy.load(model, disable=['ner'])
self.nlp = Parser._models[model]
示例4: _prob_block
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def _prob_block(sentence, pos_tagger):
"""Calculate probability that a sentence is an email block.
https://spacy.io/usage/linguistic-features
Parameters
----------
sentence : str
Line in email block.
Returns
-------
probability(signature block | line)
"""
doc = pos_tagger(sentence)
verb_count = np.sum([token.pos_ != "VERB" for token in doc])
return float(verb_count) / len(doc)
示例5: ensure_proper_language_model
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def ensure_proper_language_model(nlp: Optional["Language"]) -> None:
"""Checks if the spacy language model is properly loaded.
Raises an exception if the model is invalid."""
if nlp is None:
raise Exception(
"Failed to load spacy language model. "
"Loading the model returned 'None'."
)
if nlp.path is None:
# Spacy sets the path to `None` if
# it did not load the model from disk.
# In this case `nlp` is an unusable stub.
raise Exception(
"Failed to load spacy language model for "
"lang '{}'. Make sure you have downloaded the "
"correct model (https://spacy.io/docs/usage/)."
"".format(nlp.lang)
)
示例6: ensure_proper_language_model
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def ensure_proper_language_model(nlp):
# type: (Optional[Language]) -> None
"""Checks if the spacy language model is properly loaded.
Raises an exception if the model is invalid."""
if nlp is None:
raise Exception("Failed to load spacy language model. "
"Loading the model returned 'None'.")
if nlp.path is None:
# Spacy sets the path to `None` if
# it did not load the model from disk.
# In this case `nlp` is an unusable stub.
raise Exception("Failed to load spacy language model for "
"lang '{}'. Make sure you have downloaded the "
"correct model (https://spacy.io/docs/usage/)."
"".format(nlp.lang))
示例7: get_default_model
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def get_default_model(model_name):
err_msg = "Language model {0} not found. Please, refer https://spacy.io/usage/models"
nlp = None
if model_name is not None:
try:
nlp = spacy.load(model_name)
except (ImportError, OSError):
print(err_msg.format(model_name))
print('Using default language model')
nlp = get_default_model(EN_MODEL_SM)
return nlp
示例8: get_nlp
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def get_nlp(language, lite, lang_model=""):
err_msg = "Language model {0} not found. Please, refer https://spacy.io/usage/models"
nlp = None
if not lang_model == "" and not lang_model == "en":
try:
nlp = spacy.load(lang_model)
except ImportError:
print(err_msg.format(lang_model))
raise
elif language == 'en':
if lite:
nlp = spacy.load(EN_MODEL_DEFAULT)
else:
try:
nlp = spacy.load(EN_MODEL_MD)
except (ImportError, OSError):
print(err_msg.format(EN_MODEL_MD))
print('Using default language model')
nlp = get_default_model(EN_MODEL_DEFAULT)
elif not language == 'en':
print('Currently only English language is supported. '
'Please contribute to https://github.com/5hirish/adam_qas to add your language.')
sys.exit(0)
return nlp
示例9: __init__
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def __init__(self, *args, **kwargs):
if 'tokenize' in kwargs:
raise TypeError('``SpacyEncoder`` does not take keyword argument ``tokenize``.')
try:
import spacy
except ImportError:
print("Please install spaCy: " "`pip install spacy`")
raise
# Use English as default when no language was specified
language = kwargs.get('language', 'en')
# All languages supported by spaCy can be found here:
# https://spacy.io/models/#available-models
supported_languages = ['en', 'de', 'es', 'pt', 'fr', 'it', 'nl', 'xx']
if language in supported_languages:
# Load the spaCy language model if it has been installed
try:
self.spacy = spacy.load(language, disable=['parser', 'tagger', 'ner'])
except OSError:
raise ValueError(("Language '{0}' not found. Install using "
"spaCy: `python -m spacy download {0}`").format(language))
else:
raise ValueError(
("No tokenizer available for language '%s'. " + "Currently supported are %s") %
(language, supported_languages))
super().__init__(*args, tokenize=partial(_tokenize, tokenizer=self.spacy), **kwargs)
示例10: spacy_tokenize
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def spacy_tokenize(self, text, **kwargs):
"""
Tokenize using spaCy.
Does whatever spaCy does. See https://spacy.io/.
"""
tokens = self.NLP.tokenizer(text)
return [t.text for t in tokens]
示例11: _check_spacy
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def _check_spacy():
if spacy is None:
raise ImportError(
'Failed to import `spaCy`. '
'`spaCy` is required for POS features '
'See https://spacy.io/usage/ for installation'
'instructions.')
示例12: get_empty_candidates
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def get_empty_candidates():
"""
The mention generators always return at least one candidate, but signal
it with this special candidate
"""
return {
"candidate_spans": [[-1, -1]],
"candidate_entities": [["@@PADDING@@"]],
"candidate_entity_priors": [[1.0]]
}
# from https://spacy.io/usage/linguistic-features#custom-tokenizer-example
示例13: _discover_text
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def _discover_text(self, source: Source):
"""
Apply Sentence Boundary Detection, described here https://spacy.io/usage/linguistic-features#sbd
:param source: The source value with kind=text
"""
# this is based on SBD described here
doc = self.nlp(source.value)
for sent in doc.sents:
# TODO: would be good to add ref from source
# TODO: add filter?
text = sent.text.strip()
self.storage.train.add(text=text)
示例14: _discover_textract
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def _discover_textract(self, source: Source):
"""
Apply textract parsing, described here http://textract.readthedocs.io/en/stable/
:param source: The source value with kind=textract
"""
# TODO: add textract check
import textract
# process it
text = textract.process(self.resolve_path(file_path=source.value), language=self.storage.config.source_language)
# create new source and pass it to text processor
value = text.decode('utf-8')
new_source = Source(idx=source.idx, kind='text', value=value)
self._discover_text(new_source)
示例15: __init__
# 需要导入模块: import spacy [as 别名]
# 或者: from spacy import io [as 别名]
def __init__(self, model="en", disable=None, display_prompt=True):
if disable is None:
disable = []
try:
self._parser = spacy.load(model, disable=disable)
except OSError:
url = "https://spacy.io/models"
if display_prompt and license_prompt("Spacy {} model".format(model), url) is False:
sys.exit(0)
spacy_download(model)
self._parser = spacy.load(model, disable=disable)