关于这段代码,我有一个问题:
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必须更好地控制这种结构?
如果有人对此有解决办法或建议,我将不胜感激。
发布于 2019-11-22 15:07:41
您应该将索引的计算移到专用函数上,并进行迭代,而不是手动列出
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
]https://stackoverflow.com/questions/58995066
复制相似问题