如何降低Python3的认知复杂度

时间:2019-11-22 13:17:09

标签: python-3.x spacy

我对这段代码有疑问:

doc = nlp(text)
words = nlp(text).ents[0]
for entity in doc.ents:
   self.entity_list = [entity]

left = [
{'Left': str(words[entity.start - 1])} if words[entity.start - 1] and not words[entity.start - 1].is_punct and not
words[entity.start - 1].is_space
else
{'Left': str(words[entity.start - 2])} if words[entity.start - 2] and not words[entity.start - 2].is_punct and not
words[entity.start - 2].is_space
else
{'Left': str(words[entity.start - 3])} for entity in nlp(text).ents]

entities = [{'Entity': str(entity)} for entity in doc.ents]

right = [
{'Right': str(words[entity.end])} if (entity.end < self.entity_list[-1].end) and not words[
    entity.end].is_punct and not words[entity.end].is_space
else
{'Right': str(words[entity.end + 1])} if (entity.end + 1 < self.entity_list[-1].end) and not words[
    entity.end + 1].is_punct and not words[entity.end + 1].is_space
else
{'Right': str(words[entity.end + 2])} if (entity.end + 2 < self.entity_list[-1].end) and not words[
    entity.end + 2].is_punct and not words[entity.end + 2].is_space
else
{'Right': 'null'}
for entity in nlp(text).ents]

几天前,我正在寻求一个解决方案,关于在Python3中使用SpaCy获取实体的副词。

我找到了解决方案,并用答案更新了我的问题。但是,它看起来非常复杂且丑陋。

我的问题是:

如何在这里降低认知复杂度,以便获得更清晰易读的代码?

也许使用迭代器?还是Python3必须更好地控制这种结构的东西?

如果有人对此有解决方案或建议,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

您都应将索引的计算移至专用函数并进行迭代,而不是手动列出

def get_left_index(entity, words):
    for i in range(1, 3):
        if (
            words[entity.start - i]
            and not words[entity.start - i].is_punct
            and not words[entity.start - i].is_space
        ):
            return entity.start - i
    return entity.start - (i + 1)


def get_right_index(entity, entity_list, words):
    for i in range(3):
        if (
            (entity.end + i < entity_list[-1].end)
            and not words[entity.end + i].is_punct
            and not words[entity.end + i].is_space
        ):
            return entity.end + i


left = [
    {"Left": str(words[get_left_index(entity, words)])} for entity in nlp(text).ents
]

entities = [{"Entity": str(entity)} for entity in doc.ents]

right = [
    {"Right": str(words[get_right_index(entity, self.entity_list, words)])}
    if get_right_index(entity, self.entity_list, words) is not None
    else {"Right": "null"}
    for entity in nlp(text).ents
]