def anonymizeName(text_to_anonymize, country): # Initialize Faker fake = Faker(faker_locales_dict[country]) analyzer_results = analyzer.analyze(text=text_to_anonymize, entities=["PERSON"], language='en') matched_names = {} for match in analyzer_results: name = text_to_anonymize[match.start:match.end] if name not in names_dict: fake_name = fake.name() while (fake_name in names_dict.values()) or (fake_name in names_dict): fake_name = fake.name() names_dict[name] = fake_name matched_names[name] = fake_name else: fake_name = names_dict[name] matched_names[name] = fake_name anonymized_result = text_to_anonymize for name in matched_names: anonymized_result = anonymized_result.replace(name, matched_names[name]) return anonymized_result