import pandas as pd
import re
# 重新读取文件
df = pd.read_excel(‘/Users/ai/Desktop/Analysis/test1.xlsx’)
# 定义需要保留的词
保留词 = [
# 敬语
‘先生’, ‘女士’, ‘夫人’, ‘小姐’, ‘灵右’, ‘千古’, ‘敬輓’, ‘携妻’, ‘率子女’, ‘晚辈’, ‘先生’,
# 关系词
‘尊敬的’, ‘表姨姊夫’, ‘表姨姊’, ‘晚輩’, ‘掌夫人’, ‘内表妹夫’
]
# 脱敏函数 – 通用
def 脱敏人名(text):
if pd.isna(text) or not isinstance(text, str):
return text
text = text.strip()
if not text:
return text
# 匹配中英文名字(人名模式)
人名模式 = r'([\u4e00-\u9fa5]{2,15}|[a-zA-Z\s]{2,15}|[\u4e00-\u9fa5a-zA-Z]{2,15})’
def 替换(m):
匹配名 = m.group(1)
# 检查是否包含保留词
for 词 in 保留词:
if 词 in 匹配名:
return 匹配名 # 保留
# 检查是否以敬语结尾(如夫人、女士等)
for 敬 in [‘先生’, ‘女士’, ‘夫人’, ‘小姐’]:
if 匹配名.endswith(敬):
return 匹配名 # 保留
# 脱敏纯人名
return f”【暱稱】{匹配名}”
return re.sub(人名模式, 替换, text)
# 应用脱敏
df[‘card_heading’] = df[‘card_heading’].apply(脱敏人名)
df[‘card_signiture’] = df[‘card_signiture’].apply(脱敏人名)
# card_content 不脱敏,保持原样
print(“\n=== 脱敏后最终结果 ===”)
print(df[[‘card_heading’, ‘card_content’, ‘card_signiture’]].head(10))
# 保存结果
output_path = ‘/Users/ai/Desktop/Analysis/test1_脱敏修复.xlsx’
df.to_excel(output_path, index=False)
print(f”\n✓ 脱敏处理完成,文件已保存至:{output_path}”)
