如何在大量文本中替换性别代词?

2024-04-26 00:14:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一部小说,在写到一半的时候,我决定把一个重要的主人公从男性变成女性。我编写了一些简单的Python代码,认为我可以轻松地更改该特定字符的代词,但它意外地更改了所有字符的代词。以下是小说中的一些示例文本:

example_text = "John walked to the market. He was tired, but decided to leg it anyway, he needed the exercise! He met Joe along the way. Joe was a tall man and walked fast, during his heyday, he was an impressive athlete."

我希望将Joe(男性)更改为Jane(女性),并编写了以下简单代码:

example_text = example_text.replace(" he ", " she ")
example_text = example_text.replace(" He ", " She ")
example_text = example_text.replace(" his ", " her ")
example_text = example_text.replace(" man ", " woman ")
example_text = example_text.replace("Joe", "Jane")

但是上面的代码将乔和约翰的代词都改为女性。我现在意识到我必须使用NLP来实现这一点,但是否有一个模块或算法来实现这一点


Tags: the代码textexample小说字符replacehe