首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何降低Python3的认知复杂度

如何降低Python3的认知复杂度
EN

Stack Overflow用户
提问于 2019-11-22 13:17:09
回答 1查看 180关注 0票数 0

关于这段代码,我有一个问题:

代码语言:javascript
复制
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]

几天前,我提出了一个解决方案,涉及到获取带有SpaCy in Python3的实体的侧词。

我找到了解决办法,用答案更新了我的问题。然而,它看起来非常复杂和丑陋。

我的问题是:

如何降低这里的认知复杂性以获得更清晰、更易读的代码?

也许用迭代器?或者Python3必须更好地控制这种结构?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-22 15:07:41

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

代码语言:javascript
复制
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
]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58995066

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档