繁体   English   中英

使用Python正则表达式替换

[英]Using Python regular expressions substitution

我需要编写一个程序来识别病历中的姓名。 我该如何替换可能包含前缀,后缀和名字缩写或名字的名称,但不必每次都具有上述所有名称。 例如,我可以获取用来识别S Smith博士而不是Smith博士身份的程序。

谢谢!

这是我到目前为止的程序:

# This program removes names and email addresses occurring in a given input file and saves it in an output file.

import re
def deidentify():
    infilename = input("Give the input file name: ")
    outfilename = input("Give the output file name: ")

    infile = open(infilename,"r")
    text = infile.read()
    infile.close()

    # replace names
    nameRE = "(Ms\.|Mr\.|Dr\.|Prof\.) [A-Z](\.|[a-z]+) [A-Z][a-z]+" 
    deidentified_text = re.sub(nameRE,"**name**",text)



    outfile = open(outfilename,"w")
    print(deidentified_text, file=outfile)
    outfile.close()

deidentify()

[AZ](\\.|[az]+)

"(Ms\.|Mr\.|Dr\.|Prof\.) [A-Z](\.|[a-z]+) [A-Z][a-z]+"

正在搜索名字或名字的首字母。 您希望此部分是可选的,因此请使用捕获组。

nameRe = "(Ms\.|Mr\.|Dr\.|Prof\.)( [A-Z](\.|[a-z]+))?( [A-Z][a-z]+)"
re.sub(nameRe, r"\1\4" ,text)

?

re.sub(nameRe, r"\1\4" ,text)

表示“这部分是可选的,但即使它是空的,也仍将其视为捕获组。”

r"\\1\\4"告诉re.sub使用第一个和第四个捕获组(基本上,捕获组从显示( )开始计时。

请尝试以下操作:

((?:Ms\.|Mr\.|Dr\.|Prof\.|Mrs\.) (?:[A-Z](?:\.|(?:[a-z])+) )?[A-Z][a-z]+)

但是,我建议将此文件解析为Python数据结构(字典,对象等),然后在打印结果时可以简单地省略名称,更不用说一旦数据被处理就可以做的所有其他方便的事情。在Python程序中(例如,该患者已经陪伴我们五年以上了吗?有多少百分比的患者拥有信用卡号作为付款信息?)。

答案是,表达式需要使用\\ s来考虑空格。 一旦输入,该程序便开始工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM