我有一个字符串,我想用关键字“当与之比较”拆分它并返回两部分的字典
这两部分作为字典返回,其中“诊断”和“比较”作为键。如果句子中没有“与...比较”,则“比较”的值被指定为“无比较”
例如
如果字符串是“这是与...相比时”
输出应为:
诊断:这是(“比较时”之前的部分)
比较:(“与之比较”后的部分)
如果字符串是“多么好的”
输出应为:
诊断:多好的
比较:没有做出比较
我编写以下代码但不起作用
recomp = re.compile("When compared with")
def identifyComparison(report,recomp):
dict1={}
match = recomp.search(report)
for match in recomp.finditer(report):
dict1['diagnostic']= report[0:recomp]
dict1['comparison']= report[recomp:]
return dict1
else:
dict1['diagnostic']= report[0:recomp]
dict1['comparison']= 'no comparison made'
return dict1
提前感谢您提供任何帮助
答案 0 :(得分:2)
data, keys = "this is When compared to which is", ["diagnostic", "comparison"]
print dict(zip(keys, data.split("When compared to") + ['no comparison made']))
# {'comparison': ' which is', 'diagnostic': 'this is '}
答案 1 :(得分:0)
>>> my_string= raw_input("Enter a string: ")
Enter a string: this is when compared to which is
>>> result={}
>>> result_list = my_string.split("when compared to")
>>> if(len(result_list)==2):
... result['dignostic']=result_list[0]
... result['comparison']=result_list[1]
...
... else:
... result['dignostic']=result_list[0]
... result['comparison']='no comparison made'
>>> result
{'dignostic': 'this is ', 'comparison': ' which is'}