簡體   English   中英

當兩個字符串都存儲在python的列表中時,如何檢查字符串是否包含子字符串?

[英]How to check if a string contains substring when both are stored in lists in python?

我的主字符串在數據幀中,子字符串存儲在列表中。 我想要的輸出是找到匹配的子字符串。 這是我正在使用的代碼。

sentence2 = "Previous study: 03/03/2018 (other hospital)  Findings:   Lung parenchyma: The study reveals evidence of apicoposterior segmentectomy of LUL showing soft tissue thickening adjacent surgical bed at LUL, possibly post operation." 
blob_sentence = TextBlob(sentence2)
noun = blob_sentence.noun_phrases
df1 = pd.DataFrame(noun)
comorbidity_keywords = ["segmentectomy","lobectomy"]
matches =[]
for comorbidity_keywords[0] in df1:
    if comorbidity_keywords[0] in df1 and comorbidity_keywords[0] not in matches:
       matches.append(comorbidity_keywords)

這給我的結果是不是實際匹配的字符串。 輸出應為“節段切除術”。 但是我得到了[0,'lobectomy']。 請幫忙!!。 我試圖從這里發布的答案中尋求幫助。 檢查另一個字符串中是否存在多個字符串請幫助找出我做錯了什么?

我並沒有真正使用TextBlob,但是我有兩種方法可以幫助您實現目標。 本質上,我將句子分隔為空格,然后反復進行迭代以查看是否有匹配項。 一種方法返回一個列表,另一種返回索引值和單詞的字典。

### If you just want a list of words
def find_keyword_matches(sentence, keyword_list):
    s1 = sentence.split(' ')
    return [i for i in  s1 if i in keyword_list]

然后:

find_keyword_matches(sentence2, comorbidity_keywords)

輸出:

['segmentectomy']

對於字典:

def find_keyword_matches(sentence, keyword_list):
    s1 = sentence.split(' ')
    return {xyz.index(i):i for i in xyz if i in comorbidity_keywords}

輸出:

{17: 'segmentectomy'}

最后,一個迭代器也將打印在句子中找到單詞的位置(如果有的話):

def word_range(sentence, keyword):
    try:
        idx_start = sentence.index(keyword)
        idx_end = idx_start + len(keyword)
        print(f'Word \'{keyword}\' found within index range {idx_start} to {idx_end}')
        if idx_start > 0:
            return keyword
    except ValueError:
        pass

然后執行嵌套列表推導以擺脫None值:

found_words = [x for x in [word_range(sentence2, i) for i in comorbidity_keywords] if not x is None]

應該有一些更有效的方法來做到這一點。 但這就是我為兩個列表使用兩個for循環的結果。

for ckeyword in comorbidity_keywords:
   for keyword in df1.values.tolist():
     if any(ckeyword in key for key in keyword):
        matches.append(ckeyword)

暫無
暫無

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

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