如何在长字符串中搜索子串并在Python中创建列表?

2024-05-15 08:45:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根长长的绳子:

query = "PREFIX pht: <http://datalab.rwth-aachen.de/vocab/pht/>
         PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> 

         SELECT ?Age, ?SexTypes, ?Chest_Pain_Type, ?trestbpsD, ?cholD, 
                    ?Fasting_Glucose_Level, ?Resting_ECG_Type, ?thalachD, 
                    ?Exercise_Induced_Angina, ?oldpeakD, ?caD, ?Slope, ?Thallium_Scintigraphy, ?Diagnosis
                      WHERE {?URI a sct:125676002. }"

现在我需要创建一个由所有以“?”开头的子字符串组成的列表。所以列表应该如下所示:

schema = ['Age', 'Sex', 'Chest_Pain_Type', 'Trestbps', 'Chol', 'Fasting_Glucose_Level', 'Resting_ECG_Type', 'ThalachD', 
             'Exercise_Induced_Angina', 'OldpeakD', 'CaD', 'Slope', 'Thallium_Scintigraphy', 'Diagnosis']

我试过str.startswith(str, beg=0,end=len(string))

但并不像我想象的那样。如何在Python中实现它?你知道吗


Tags: httpageprefixtyperdflevelecgpain
1条回答
网友
1楼 · 发布于 2024-05-15 08:45:46

使用正则表达式:

import re
query = """PREFIX pht: <http://datalab.rwth-aachen.de/vocab/pht/>
         PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> 

         SELECT ?Age, ?SexTypes, ?Chest_Pain_Type, ?trestbpsD, ?cholD, 
                    ?Fasting_Glucose_Level, ?Resting_ECG_Type, ?thalachD, 
                    ?Exercise_Induced_Angina, ?oldpeakD, ?caD, ?Slope, ?Thallium_Scintigraphy, ?Diagnosis
                      WHERE {?URI a sct:125676002. }"""

#print re.findall("\?\w+", query)
print([i.replace("?", "") for i in re.findall("\?\w+", query)])

输出:

['Age', 'SexTypes', 'Chest_Pain_Type', 'trestbpsD', 'cholD', 'Fasting_Glucose_Level', 'Resting_ECG_Type', 'thalachD', 'Exercise_Induced_Angina', 'oldpeakD', 'caD', 'Slope', 'Thallium_Scintigraphy', 'Diagnosis', 'URI']

相关问题 更多 >