Python 仅当字符串包含';时执行';?
仅当搜索的字符串包含逗号时,我才尝试执行一组代码 下面是我需要解析的一组行的示例(name是这个以制表符分隔的文件的列标题,该列(令人讨厌)包含名称、程度和实践领域:Python 仅当字符串包含';时执行';?,python,regex,Python,Regex,仅当搜索的字符串包含逗号时,我才尝试执行一组代码 下面是我需要解析的一组行的示例(name是这个以制表符分隔的文件的列标题,该列(令人讨厌)包含名称、程度和实践领域: name Sam da Man J.D.,CEP Green Eggs Jr. Ed.M.,CEP Argle Bargle Sr. MA Cersei Lannister M.A. Ph.D. 我的问题是,有些行包含逗号,后跟代表专业人员“实践领域”的首字母缩略词,有些
name
Sam da Man J.D.,CEP
Green Eggs Jr. Ed.M.,CEP
Argle Bargle Sr. MA
Cersei Lannister M.A. Ph.D.
我的问题是,有些行包含逗号,后跟代表专业人员“实践领域”的首字母缩略词,有些行则不包含
我的代码依赖于每一行都包含一个逗号的原则,现在我必须修改代码以解释没有逗号的行
def parse_ieca_gc(s):
########################## HANDLE NAME ELEMENT ###############################
degrees = ['M.A.T.','Ph.D.','MA','J.D.','Ed.M.', 'M.A.', 'M.B.A.', 'Ed.S.', 'M.Div.', 'M.Ed.', 'RN', 'B.S.Ed.', 'M.D.']
degrees_list = []
# separate area of practice from name and degree and bind this to var 'area'
split_area_nmdeg = s['name'].split(',')
area = split_area_nmdeg.pop() # when there is no area of practice and hence no comma, this pops out the name + deg and leaves an empty list, that's why 'print split_area_nmdeg' returns nothing and 'area' returns the name and deg when there's no comma
print 'split area nmdeg'
print area
print split_area_nmdeg
# Split the name and deg by spaces. If there's a deg, it will match with one of elements and will be stored deg list. The deg is removed name_deg list and all that's left is the name.
split_name_deg = re.split('\s',split_area_nmdeg[0])
for word in split_name_deg:
for deg in degrees:
if deg == word:
degrees_list.append(split_name_deg.pop())
name = ' '.join(split_name_deg)
# area of practice
category = area
似乎re.search()和re.match()都不起作用,因为它们返回的是实例,而不是布尔值,那么如果有逗号,我应该用什么来判断呢
if re.match(...) is not None :
不要使用布尔值。Match在成功时返回MatchObject实例,失败时返回None。python中查看字符串是否包含字符的最简单方法是在中使用
。例如:
if ',' in s['name']:
您已经在搜索逗号。只需使用该搜索的结果:
split_area_nmdeg = s['name'].split(',')
if len(split_area_nmdeg) > 2:
print "Your old code goes here"
else:
print "Your new code goes here"
没问题!一定要查看python文档,虽然这一部分有点冗长,但它非常好:P