【问题标题】:How to search for substrings in a long string and create a list in Python?如何在长字符串中搜索子字符串并在 Python 中创建列表?
【发布时间】:2018-03-20 10:48:41
【问题描述】:

我的字符串很长:

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 中做到这一点?

【问题讨论】:

  • 为什么 ?URI 不在结果中?
  • vbar,不错的收获!实际上,我不需要 ?URI。我想解释一下,但后来认为这会增加问题的复杂性。
  • 是的,它确实增加了复杂性...... :-) 正则表达式可以找到所有以'?'开头的单词(见下文),但如果你想根据更大的上下文跳过其中的一些,你需要更多的步骤......

标签: python string substring


【解决方案1】:

使用正则表达式:

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']

【讨论】:

  • 非常感谢您拯救了我的一天!很抱歉,如果我想要在“WHERE”之前出现的所有事件怎么办?我们能以某种方式限制这一点吗?我对 Python 很陌生。
  • 当然。您可以修剪查询字符串以排除“WHERE”之后的内容。例如:query = query[:query.find("WHERE")]
  • 嗨,Rakesh,效果很好!我已经接受了答案,但由于我没有足够的声誉,所以可能没有得到反映。
  • 对不起,我现在这样做了!我对 StackOverflow 也很陌生。谢谢:)
猜你喜欢
  • 2016-04-21
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 2019-10-06
相关资源
最近更新 更多