簡體   English   中英

在句子中搜索關鍵詞(Python)

[英]Search key words in a sentence (Python)

我有以下代碼:

import re

sentences=['the Research and development cost of the year']
rdterms=['research and development']
rdterms_regex = [re.compile(r'\b' + term + r'\b') 
                    for term in rdterms] 

def rdsentence(sentence:str):
    """Checks whether a sentence is R&D-oriented."""
    for term in rdterms_regex:    
        if term.search(sentence, re.IGNORECASE): 
            return True 
    return False

for sentence in sentences:
    print(rdsentence(sentence))

代碼的目的是檢測rdterms中的關鍵詞(即'research and development')是否出現在句子中(即'the Research and development cost of the year')。

如果這句話是“當年的研發費用”——當前報告“真”——正確。

如果句子是“當年的研發成本”--當前報告“False”--我要它報告“True”。

如果這句話是“研發”——當前報告“假”——我要它報告“真”。

我的代碼有什么問題? 謝謝!

在編譯正則表達式時指定re.IGNORECASE ,而不是在搜索中:

rdterms_regex = [re.compile(r'\b' + term + r'\b', re.IGNORECASE) 
                    for term in rdterms] 

def rdsentence(sentence:str):
    """Checks whether a sentence is R&D-oriented."""
    for term in rdterms_regex:    
        if term.search(sentence): 
            return True 
    return False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM