該程式應該接受文本并用他們的首字母替換某些人的實際姓名。它接受兩個輸入:
- 文本(示例)作為 string1
Sara amity 醫生于 1999 年 3 月 12 日會見了特工 Binod Rastogi。特工 smike smith和醫生 amy wills以及特工湯姆愛德華茲也在秘密會議上。
- 要隱藏為 cens_element 的人:
醫生/代理(不區分大小寫)
import re
string1 = input('Enter the text to censor the names in:')
print('=========================')
print('\n whose names do you want to censor?')
cens_element = input()
regobj = re.compile(f'{cens_element} (\w)\w* (\w)\w*', re.IGNORECASE)
final = regobj.sub('%s '%(cens_element) (r'\1.'.upper()) ' ' (r'\2.'.upper()), string1)
#\1 and \2 for the first and second groups for name initials (\w) respectively.
print('\n')
print('='*len(cens_element))
print('\n')
print(final)
'final' 變數賦值中的 upper() 方法似乎不起作用,因為它們沒有大寫首字母
輸出:(cens_element=醫生)
S.a. 醫生 1999 年 3 月 12 日與特工 Binod Rastogi 會面。特工 smike smith 和醫生 aw 以及特工湯姆愛德華茲也在秘密會議上。
預期產出
S. A.醫生于 1999 年 3 月 12 日會見了特工 Binod Rastogi。特工 smike smith 和醫生AW以及特工湯姆愛德華茲也在秘密會議上。
如何獲得所需的輸出?
uj5u.com熱心網友回復:
您的問題.upper()在于它適用于字串,例如'\1' 在替換發生之前。
對于這種花哨的格式,您可以對sub方法使用“回呼函式”而不是字串,這在格式化替換文本時提供了很大的靈活性。
例子:
import re
text = """
Doctor Sara Amity met agent Binod Rastogi on 12th March 1999.
Agent smike smith and doctor amy wills along with agent Tom edwards were also in the secret meeting.
"""
title = 'Doctor'
ptrn = re.compile(f'{title} (\w)\w* (\w)\w*',re.IGNORECASE)
def replfunc(matchobj):
grps = matchobj.groups()
return f'{title} {grps[0].upper()}. {grps[1].upper()}.'
res = ptrn.sub(replfunc,text,count=0)
print(res)
結果:
SA 博士于 1999 年 3 月 12 日會見了特工 Binod Rastogi。特工 smike smith 和 AW 博士以及特工湯姆愛德華茲也在秘密會議上。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/348230.html
上一篇:為什么Python中的原子分組比簡單的非捕獲交替慢?
下一篇:獲取字串中出現頻率最高的所有數字
