繁体   English   中英

Python If-Else 语句

[英]Python If-Else Statement

目的是从文本中提取单词定义或指示之前的句子

def extract(doc):

    if( len(doc) != 0 ):
        if ('Definition' in doc):
                sentence = doc.split('Definition')[0]  

        elif ('Definition' not in doc and 'indications' in doc):
                sentence = doc.split('indications')[0]

        return sentence 
    else :
        return doc

它返回错误:UnboundLocalError:分配前引用的局部变量“句子”

你可以试试下面的代码。这是一个简单的方法。我们可以在 if 和 elif 语句之后打印输出。如果没有单词“Dosage”和“Contradictions”,我们也可以添加一个 else 语句打印在句子中。

def just_indication(doc):

if( len(doc) != 0 ):
    if ('Dosage' in doc):
            sentence = doc.split('Dosage')[0]  
            print(sentence)
    elif ('Dosage' not in doc and 'Contraindications' in doc):
            sentence = doc.split('Contraindications')[0]
            print(sentence)
     
    else:
         print("Error! word Dosage and Contraindications not present in doc")
    
else:
    print("doc empty")
           
just_indication("this is the sentence which has the word Contraindications in it")

我认为这是因为您在 if 语句中声明了“句子”,请尝试在您的 def 之后立即声明它,如下所示:

def just_indication(doc):
    sentence = ""
    if( len(doc) != 0 ):
        if ('Dosage' in doc):
                sentence = doc.split('Dosage')[0]  

        elif ('Dosage' not in doc and 'Contraindications' in doc):
                sentence = doc.split('Contraindications')[0]

        return sentence 
    else :
        return doc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM