Reverse the gender of a string

Revision as of 17:59, 2 February 2017 by PureFox (talk | contribs) (Added Kotlin)

The task is to create a function that reverses the gender of the text of a string. The function should take one arguments being a string to undergo the sex change. The returned string should contain this initial string, with all references to gender switched.

Reverse the gender of a string is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

<lang pseudocode>print rev_gender("She was a soul stripper. She took my heart!") He was a soul stripper. He took my heart!</lang>

FreeBASIC

Although in principle all gender-related words in the dictionary could be swapped, I've only attempted to swap the 3rd person pronouns, possessive pronouns and possessive adjectives here. Even then, without code to understand the context, some swaps are ambiguous - for example 'her' could map to 'his' or 'him' and 'his' could map to 'her' or 'hers'.

To avoid swapping words which have already been swapped, thereby nullifying the original swap, I've appended an underscore to each replacement word and then removed all the underscores when all swaps have been made. This assumes, of course, that the text didn't include any underscores to start with. <lang freebasic>' FB 1.05.0 Win64

Function isWordChar(s As String) As Boolean

 Return ("a" <= s AndAlso s <= "z") OrElse ("A" <= s AndAlso s <= "Z") OrElse("0" <= s AndAlso s <= "9") OrElse s = "_"

End Function

Function revGender(s As Const String) As String

 If s = "" Then Return ""
 Dim t As String = s 
 Dim word(1 To 10) As String = {"She", "she", "Her",  "her",  "hers", "He",   "he",   "His",  "his",  "him"}
 Dim repl(1 To 10) As String = {"He_", "he_", "His_", "his_" ,"his_", "She_", "she_", "Her_", "her_", "her_"}
 Dim As Integer index, start, after 
 For i As Integer = 1 To 10
   start = 1
   While start <= Len(t) - Len(word(i)) + 1 
     index = Instr(start, t, word(i))      
     If index = 0 Then Exit While
     after = index + Len(word(i))
     If index = 1 AndAlso after <= Len(t) AndAlso CInt(isWordChar(Mid(t, after, 1))) Then 
       start = after
       Continue While
     End If
     If index > 1 AndAlso after <= Len(t) AndAlso _
       (CInt(isWordChar(Mid(t, index - 1, 1))) OrElse CInt(isWordChar(Mid(t, after, 1)))) Then 
       start = after
       Continue While
     End If
     t = Left(t, index - 1) + repl(i) + Mid(t, after)
     start = index + Len(repl(i))
   Wend
 Next
 ' now remove all underscores
 For i As Integer = Len(t) To 1 Step -1
   If Mid(t, i, 1) = "_" Then
     t = Left(t, i - 1) + Mid(t, i + 1)
   End If
 Next 
 Return t

End Function

Print revGender("She was a soul stripper. She took his heart!") Print revGender("He was a soul stripper. He took her heart!") Print revGender("She wants what's hers, he wants her and she wants him!") Print revGender("Her dog belongs to him but his dog is hers!") Print Print "Press any key to quit" Sleep</lang>

Output:
He was a soul stripper. He took her heart!
She was a soul stripper. She took his heart!
He wants what's his, she wants his and he wants her!
His dog belongs to her but her dog is his!

J

Note that we cannot do a good job for the general case of english text using simple rules. For example, consider:

  • Give her the book. It is her book.
  • Give him the book. It is his book.


For this simple example, to determine whether to change her to him or his we would need a grammatical representation of the surrounding context.

So, for now, we limit ourselves to the simple case specified in the task example, and do not even do all that great of a job there, either:

<lang J>cheaptrick=: rplc&(;:'She He He She')</lang>

And, the task example:

<lang J> cheaptrick 'She was a soul stripper. She took my heart!' He was a soul stripper. He took my heart!

  cheaptrick cheaptrick 'She was a soul stripper. She took my heart!'

She was a soul stripper. She took my heart!</lang>

Java

Translation of: J

<lang java>public class ReallyLameTranslationOfJ {

   public static void main(String[] args) {
       String s = "She was a soul stripper. She took my heart!";
       System.out.println(cheapTrick(s));
       System.out.println(cheapTrick(cheapTrick(s)));
   }
   static String cheapTrick(String s) {
       if (s.contains("She"))
           return s.replaceAll("She", "He");
       else if(s.contains("He"))
           return s.replaceAll("He", "She");
       return s;
   }

}</lang>

He was a soul stripper. He took my heart!
She was a soul stripper. She took my heart!

Kotlin

This program uses a similar approach to the FreeBASIC entry: <lang scala>// version 1.0.6

fun reverseGender(s: String): String {

   var t = s
   val words = listOf("She", "she", "Her",  "her",  "hers", "He",   "he",   "His",  "his",  "him")
   val repls = listOf("He_", "he_", "His_", "his_" ,"his_", "She_", "she_", "Her_", "her_", "her_")
   for (i in 0 until words.size) {
       val r = Regex("""\b${words[i]}\b""")
       t = t.replace(r, repls[i])
   }
   return t.replace("_", "")

}

fun main(args: Array<String>) {

   println(reverseGender("She was a soul stripper. She took his heart!"))
   println(reverseGender("He was a soul stripper. He took her heart!"))
   println(reverseGender("She wants what's hers, he wants her and she wants him!"))
   println(reverseGender("Her dog belongs to him but his dog is hers!"))

}</lang>

Output:
He was a soul stripper. He took her heart!
She was a soul stripper. She took his heart!
He wants what's his, she wants his and he wants her!
His dog belongs to her but her dog is his!

PowerShell

Translation of: J

(Made more PowerShelly.)

<lang PowerShell> function Switch-Gender ([string]$String) {

   if ($String -match "She")
   {
       $String.Replace("She", "He")
   }
   elseif ($String -match "He")
   {
       $String.Replace("He", "She")
   }
   else
   {
       $String
   }

}

Switch-Gender "She was a soul stripper. She took my heart!" Switch-Gender (Switch-Gender "She was a soul stripper. She took my heart!") </lang>

Output:
He was a soul stripper. He took my heart!
She was a soul stripper. She took my heart!

Python

<lang Python>#!/usr/bin/env python

  1. -*- coding: utf-8 -*- #

import re male2female=u"""maleS femaleS, maleness femaleness, him her, himself herself, his her, his hers, he she, Mr Mrs, Mister Missus, Ms Mr, Master Miss, Master Mistress, uncleS auntS, nephewS nieceS, sonS daughterS, grandsonS granddaughterS, brotherS sisterS, man woman, men women, boyS girlS, paternal maternal, grandfatherS grandmotherS, GodfatherS GodmotherS, GodsonS GoddaughterS, fiancéS fiancéeS, husband wife, husbands wives, fatherS motherS, bachelorS spinsterS, bridegroomS brideS, widowerS widowS, KnightS DameS, Sir DameS, KingS QueenS, DukeS DuchessES, PrinceS PrincessES, Lord Lady, Lords Ladies, MarquessES MarchionessES, EarlS CountessES, ViscountS ViscountessES, ladS lassES, sir madam, gentleman lady, gentlemen ladies, BaronS BaronessES, stallionS mareS, ramS eweS, coltS fillieS, billy nanny, billies nannies, bullS cowS, godS goddessES, heroS heroineS, shirtS blouseS, undies nickers, sweat glow, jackarooS jillarooS, gigoloS hookerS, landlord landlady, landlords landladies, manservantS maidservantS, actorS actressES, CountS CountessES, EmperorS EmpressES, giantS giantessES, heirS heiressES, hostS hostessES, lionS lionessES, managerS manageressES, murdererS murderessES, priestS priestessES, poetS poetessES, shepherdS shepherdessES, stewardS stewardessES, tigerS tigressES, waiterS waitressES, cockS henS, dogS bitchES, drakeS henS, dogS vixenS, tomS tibS, boarS sowS, buckS roeS, peacockS peahenS, gander goose, ganders geese, friarS nunS, monkS nunS, Adam Eve, Aaron Erin, Adrian Adriana, Aidrian Aidriana, Alan Alaina, Albert Alberta, Alex Alexa, Alex Alexis, Alexander Alaxandra, Alexander Alexandra, Alexander Alexis, Alexandra Alexander, Alexei Alexis, Alfred Alfreda, Andrew Andrea, Andrew Andrea, Angel Angelica, Anthony Antonia, Antoine Antoinette, Ariel Arielle, Ashleigh Ashley, Barry Barrie, Benedict Benita, Benjamin Benjamine, Bert Bertha, Brandon Brandi, Brendan Brenda, Briana Brian, Brian Rianne, Caela Caesi, Caeleb Caeli, Carl Carla, Carl Carly, Carolus Caroline, Charles Caroline, Charles Charlotte, Christian Christa, Christian Christiana, Christian Christina, Christopher Christina, Christopher Christine, Clarence Claire, Claude Claudia, Clement Clementine, Cory Cora, Daniel Daniella, Daniel Danielle, David Davena, David Davida, David Davina, Dean Deanna, Devin Devina, Edward Edwina, Edwin Edwina, Emil Emilie, Emil Emily, Eric Erica, Erick Erica, Erick Ericka, Ernest Ernestine, Ethan Etha, Ethan Ethel, Eugene Eugenie, Fabian Fabia, Francesco Francesca, Frances Francesca, Francis Frances, Francis Francine, Frederick Fredrica, Fred Freda, Fredrick Frederica, Gabriel Gabriella, Gabriel Gabrielle, Gene Jean, George Georgia, george georgina, George Georgina, Gerald Geraldine, Giovanni Giovanna, Glen Glenn, Harry Harriet, Harry Harriette, Heather Heath, Henry Henrietta, Horace Horatia, Ian Iana, Ilija Ilinka, Ivo Ivy, Ivan Ivy, Jack Jackelyn, Jack Jackie, Jack Jaclyn, Jack Jacqueline, Jacob Jacobine, James Jamesina, James Jamie, Jaun Jaunita, Jayda Jayden, Jesse Jessica, Jesse Jessie, Joe Johanna, Joel Joelle, John Jean, John Joan, John Johanna, Joleen Joseph, Jon Joane, Joseph Josephine, Joseph Josphine, Julian Julia, Julian Juliana, Julian Julianna, Justin Justine, Karl Karly, Kendrick Kendra, Ken Kendra, Kian Kiana, Kyle Kylie, Laurence Laura, Laurence Lauren, Laurence Laurencia, Leigh Leigha, Leon Leona, Louis Louise, Lucas Lucia, Lucian Lucy, Luke Lucia, Lyle Lyla, Maria Mario, Mario Maricela, Mark Marcia, Marshall Marsha, Martin martina, Martin Martina, Martin Martine, Max Maxine, Michael Michaela, Michael Micheala, Michael Michelle, Mitchell Michelle, Nadir Nadira, Nicholas Nicole, Nicholas Nicki, Nicholas Nicole, Nicky Nikki, Nicolas Nicole, Nigel Nigella, Noel Noelle, Oen Ioena, Oliver Olivia, Patrick Patricia, Paul Paula, Phillip Phillipa, Phillip Pippa, Quintin Quintina, Reginald Regina, Richard Richardine, Robert Roberta, Robert Robyn, Ronald Rhonda, Ryan Rhian, Ryan Ryanne, Samantha Samuel, Samuel Samantha, Samuel Sammantha, Samuel Samuela, Sean Sian, Sean Siana, Shaun Shauna, Sheldon Shelby, Sonny Sunny, Stephan Stephanie, Stephen Stephanie, Steven Stephanie, Terry Carol, Terry Carrol, Theodore Theadora, Theodore Theodora, Theodore Theordora, Thomas Thomasina, Tristan Tricia, Tristen Tricia, Ulric Ulrika, Valentin Valentina, Victor Victoria, William Wilhelmina, William Willa, William Willamina, Xavier Xaviera, Yarden Yardena, Zahi Zahira, Zion Ziona"""

re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]

switch={} words=[]


re_plural=re.compile("E*S$") re_ES=re.compile("ES$")

def gen_pluralize(m,f):

  1. do plurals first
 yield re_plural.sub("",m),re_plural.sub("",f)
 yield re_ES.sub("es",m),re_ES.sub("es",f)
 yield re_plural.sub("s",m),re_plural.sub("s",f)

def gen_capitalize_pluralize(m,f):

 for m,f in gen_pluralize(m,f):
   yield m.capitalize(), f.capitalize()
   yield m,f

def gen_switch_role_capitalize_pluralize(m,f):

 for m,f in gen_capitalize_pluralize(m,f):
   yield m,f
   yield f,m

for m,f in m2f:

 for xy,xx in gen_switch_role_capitalize_pluralize(m,f):
   if xy not in switch: 
     switch[xy]=xx
     words.append(xy)

words="|".join(words)

re_word=re.compile(ur"\b("+words+ur")\b")

text=uWhen a new-hatched savage running wild about his native woodlands in a grass clout, followed by the nibbling goats, as if he were a green sapling; even then, in Queequeg's ambitious soul, lurked a strong desire to see something more of Christendom than a specimen whaler or two. His father was a High Chief, a King; his uncle a High Priest; and on the maternal side he boasted aunts who were the wives of unconquerable warriors. There was excellent blood in his veins-royal stuff; though sadly vitiated, I fear, by the cannibal propensity he nourished in his untutored youth.


def rev_gender(text):

 text=re_word.split(text)
 return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]

print rev_gender(text)</lang> Output:

When a new-hatched savage running wild about her native
woodlands in a grass clout, followed by the nibbling goats, as if
she were a green sapling; even then, in Queequeg's ambitious soul,
lurked a strong desire to see something more of Christendom than
a specimen whaler or two. Her mother was a High Chief, a Queen;
her aunt a High Priestess; and on the paternal side she boasted uncles
who were the husbands of unconquerable warriors. There was excellent
blood in her veins-royal stuff; though sadly vitiated, I fear,
by the cannibal propensity she nourished in her untutored youth.

Racket

<lang racket>

  1. lang at-exp racket

(define raw-mapping @~a{

 maleS femaleS, maleness femaleness, him her, himself herself, his her, his
 hers, he she, Mr Mrs, Mister Missus, Ms Mr, Master Miss, MasterS MistressES,
 uncleS auntS, nephewS nieceS, sonS daughterS, grandsonS granddaughterS,
 brotherS sisterS, man woman, men women, boyS girlS, paternal maternal,
 grandfatherS grandmotherS, GodfatherS GodmotherS, GodsonS GoddaughterS,
 fiancéS fiancéeS, husband wife, husbands wives, fatherS motherS, bachelorS
 spinsterS, bridegroomS brideS, widowerS widowS, KnightS DameS, Sir DameS,
 KingS QueenS, DukeS DuchessES, PrinceS PrincessES, Lord Lady, Lords Ladies,
 MarquessES MarchionessES, EarlS CountessES, ViscountS ViscountessES, ladS
 lassES, sir madam, gentleman lady, gentlemen ladies, BaronS BaronessES,
 stallionS mareS, ramS eweS, coltS fillieS, billy nanny, billies nannies,
 bullS cowS, godS goddessES, heroS heroineS, shirtS blouseS, undies nickers,
 sweat glow, jackarooS jillarooS, gigoloS hookerS, landlord landlady,
 landlords landladies, manservantS maidservantS, actorS actressES, CountS
 CountessES, EmperorS EmpressES, giantS giantessES, heirS heiressES, hostS
 hostessES, lionS lionessES, managerS manageressES, murdererS murderessES,
 priestS priestessES, poetS poetessES, shepherdS shepherdessES, stewardS
 stewardessES, tigerS tigressES, waiterS waitressES, cockS henS, dogS bitchES,
 drakeS henS, dogS vixenS, tomS tibS, boarS sowS, buckS roeS, peacockS
 peahenS, gander goose, ganders geese, friarS nunS, monkS nunS, Adam Eve,
 Aaron Erin, Adrian Adriana, Aidrian Aidriana, Alan Alaina, Albert Alberta,
 Alex Alexa, Alex Alexis, Alexander Alaxandra, Alexander Alexandra, Alexander
 Alexis, Alexandra Alexander, Alexei Alexis, Alfred Alfreda, Andrew Andrea,
 Angel Angelica, Anthony Antonia, Antoine Antoinette, Ariel Arielle, Ashleigh
 Ashley, Barry Barrie, Benedict Benita, Benjamin Benjamine, Bert Bertha,
 Brandon Brandi, Brendan Brenda, Briana Brian, Brian Rianne, Caela Caesi,
 Caeleb Caeli, Carl Carla, Carl Carly, Carolus Caroline, Charles Caroline,
 Charles Charlotte, Christian Christa, Christian Christiana, Christian
 Christina, Christopher Christina, Christopher Christine, Clarence Claire,
 Claude Claudia, Clement Clementine, Cory Cora, Daniel Daniella, Daniel
 Danielle, David Davena, David Davida, David Davina, Dean Deanna, Devin
 Devina, Edward Edwina, Edwin Edwina, Emil Emilie, Emil Emily, Eric Erica,
 Erick Erica, Erick Ericka, Ernest Ernestine, Ethan Etha, Ethan Ethel, Eugene
 Eugenie, Fabian Fabia, Francesco Francesca, Frances Francesca, Francis
 Frances, Francis Francine, Frederick Fredrica, Fred Freda, Fredrick
 Frederica, Gabriel Gabriella, Gabriel Gabrielle, Gene Jean, George Georgia,
 George Georgina, Gerald Geraldine, Giovanni Giovanna, Glen Glenn, Harry
 Harriet, Harry Harriette, Heather Heath, Henry Henrietta, Horace Horatia, Ian
 Iana, Ilija Ilinka, Ivo Ivy, Ivan Ivy, Jack Jackelyn, Jack Jackie, Jack
 Jaclyn, Jack Jacqueline, Jacob Jacobine, James Jamesina, James Jamie, Jaun
 Jaunita, Jayda Jayden, Jesse Jessica, Jesse Jessie, Joe Johanna, Joel Joelle,
 John Jean, John Joan, John Johanna, Joleen Joseph, Jon Joane, Joseph
 Josephine, Joseph Josphine, Julian Julia, Julian Juliana, Julian Julianna,
 Justin Justine, Karl Karly, Kendrick Kendra, Ken Kendra, Kian Kiana, Kyle
 Kylie, Laurence Laura, Laurence Lauren, Laurence Laurencia, Leigh Leigha,
 Leon Leona, Louis Louise, Lucas Lucia, Lucian Lucy, Luke Lucia, Lyle Lyla,
 Maria Mario, Mario Maricela, Mark Marcia, Marshall Marsha, Martin martina,
 Martin Martine, Max Maxine, Michael Michaela, Michael Micheala, Michael
 Michelle, Mitchell Michelle, Nadir Nadira, Nicholas Nicole, Nicholas Nicki,
 Nicky Nikki, Nicolas Nicole, Nigel Nigella, Noel Noelle, Oen Ioena, Oliver
 Olivia, Patrick Patricia, Paul Paula, Phillip Phillipa, Phillip Pippa,
 Quintin Quintina, Reginald Regina, Richard Richardine, Robert Roberta, Robert
 Robyn, Ronald Rhonda, Ryan Rhian, Ryan Ryanne, Samantha Samuel, Samuel
 Samantha, Samuel Sammantha, Samuel Samuela, Sean Sian, Sean Siana, Shaun
 Shauna, Sheldon Shelby, Sonny Sunny, Stephan Stephanie, Stephen Stephanie,
 Steven Stephanie, Terry Carol, Terry Carrol, Theodore Theadora, Theodore
 Theodora, Theodore Theordora, Thomas Thomasina, Tristan Tricia, Tristen
 Tricia, Ulric Ulrika, Valentin Valentina, Victor Victoria, William
 Wilhelmina, William Willa, William Willamina, Xavier Xaviera, Yarden Yardena,
 Zahi Zahira, Zion Ziona})

(define flip-map (make-hash))

(for ([m (reverse (regexp-split #px"\\s*,\\s*" raw-mapping))])

 (define p (string-split m))
 (unless (= 2 (length p)) (error "Bad raw data"))
 (define (map! x y)
   (hash-set! flip-map (string-foldcase x) (string-foldcase y))
   (hash-set! flip-map (string-upcase x) (string-upcase y))
   (hash-set! flip-map (string-titlecase x) (string-titlecase y)))
 (define (2map! x y) (map! x y) (map! y x))
 (apply 2map! p)
 (apply 2map! (map (λ(x) (regexp-replace #rx"E?S$" x "")) p)))

(define (reverse-gender str)

 (regexp-replace* #px"\\w+" str
   (λ(word) (hash-ref flip-map word word))))

(displayln (reverse-gender @~a{ She was a soul stripper. She took my heart!

When a new-hatched savage running wild about his native woodlands in a grass clout, followed by the nibbling goats, as if he were a green sapling; even then, in Queequeg's ambitious soul, lurked a strong desire to see something more of Christendom than a specimen whaler or two. His father was a High Chief, a King; his uncle a High Priest; and on the maternal side he boasted aunts who were the wives of unconquerable warriors. There was excellent blood in his veins-royal stuff; though sadly vitiated, I fear, by the cannibal propensity he nourished in his untutored youth. })) </lang>

Output:
He was a soul stripper. He took my heart!

When a new-hatched savage running wild about her native
woodlands in a grass clout, followed by the nibbling goats, as if
she were a green sapling; even then, in Queequeg's ambitious soul,
lurked a strong desire to see something more of Christendom than
a specimen whaler or two. Her mother was a High Chief, a Queen;
her aunt a High Priestess; and on the paternal side she boasted uncles
who were the husbands of unconquerable warriors. There was excellent
blood in her veins-royal stuff; though sadly vitiated, I fear,
by the cannibal propensity she nourished in her untutored youth.

REXX

Not much effort was put into compressing the words (as far as pluralizing and constructing the various forms of words).   More code could be written to parse words that have a minus or hyphen. <lang rexx>/*REXX program to reverse genderize a text string. */ sw=linesize()-1 /*get the screen width less one.*/ parse var sw . @ @. !. /*nullify some REXX variables. */

old='When a new-hatched savage running wild about his native woodlands',

   'in a grass clout, followed by the nibbling goats, as if he were a',
   'green sapling; even then, in Queequegs ambitious soul, lurked a',
   'strong desire to see something more of Christendom than a',
   'specimen whaler or two. His father was a High Chief, a King; his',
   'uncle a High Priest; and on the maternal side he boasted aunts',
   'who were the wives of unconquerable warriors. There was excellent',
   'blood in his veins-royal stuff; though sadly vitiated, I fear, by',
   'the cannibal propensity he nourished in his untutored youth.'

call tell old, ' old ' /*show a nicely parse "old" text.*/ @=@ 'abboty abbess' @=@ 'actor actress' @=@ 'adonis belle' @=@ 'adulterer adultress' @=@ 'archer archeress' @=@ 'administrator administratrix' @=@ 'ambassador ambassadress' @=@ 'anchor anchress' @=@ 'archduke archduchess' @=@ 'author authoress' @=@ 'aviator aviatrix aviators aviatrices' @=@ 'bachelor bachelorette bachelor spinster' @=@ 'ballerino ballerina' @=@ 'barkeeper barkeeperess' @=@ 'barman barwoman barmen barwomen barman barmaid' @=@ 'baron baroness baronet baronetess bt btss' @=@ 'batboy batgirl' @=@ 'batman batwoman' @=@ 'benefactor benefactress' @=@ 'billy nanny billies nannies' @=@ 'blond blonde' @=@ 'boar sow' @=@ 'boy girl boy-band girl-band boy-oh-boy girl-oh-girl boydom girldom' @=@ 'boyfriend girlfriend boyhood girlhood boyish girlish boyism girlism' @=@ 'boyish-looking girlish-looking boyishly girlishly boyishness girlishness' @=@ 'boylike girllike boylikeness girllikeness boyliker girlliker' @=@ 'boylikest girllikest boyscout girlscout boyship girlship' @=@ 'brother sister brotherhood sisterhood brotherly sisterly' @=@ 'buck doe' @=@ 'bull cow bullshit cowshit' @=@ 'butcher butcheress' @=@ 'caliph calafia caliph calipha' @=@ 'caterer cateress' @=@ 'chanter chantress' @=@ 'chairman chairwoman chairmen chairwomen' @=@ 'chief chiefess' @=@ 'clerk clerkess' @=@ 'coadjutor cadutrix' @=@ 'cock hen' @=@ 'colt fillie' @=@ 'commedian comedienne' @=@ 'conductor conductress' @=@ 'confessor confessoress' @=@ 'conquer conqueress' @=@ 'cook cookess' @=@ 'count countess' @=@ 'cowboy cowgirl cowman cowwoman cowmen cowwomen' @=@ 'czar czarina' @=@ 'dad mom dada mama daddy mommy daddies mommies' @=@ 'deacon deaconess' @=@ 'debutant debutante' @=@ 'demon demoness' @=@ 'devil deviless' @=@ 'director directress' @=@ 'divine divineress' @=@ 'divorce divorcee' @=@ 'doctor doctress' @=@ 'dominator dominatrix dominators dominatrices' @=@ 'dragon dragoness' @=@ 'drone bee' @=@ 'drake duck' @=@ 'dude dudette' @=@ 'duke duchess' @=@ 'earl countess' @=@ 'editor editress editor editrix' @=@ 'elector electress' @=@ 'emperor empress' @=@ 'enchanter enchantress' @=@ 'executor executrix executor executres' @=@ 'ex-husband ex-wife ex-husbands ex-wives ex-boyfriend ex-girlfriend' @=@ 'father mother fatherhood motherhood fatherphocker motherphocker' @=@ 'fiance fiancee' @=@ 'fisherman fisherwoman fishermen fisherwomen' @=@ 'fishman fishwoman fishmen fishwomen' @=@ 'foreman forewoman foremen forewomen' @=@ 'friar nun' @=@ 'gander goose ganders geese' @=@ 'giant giantess' @=@ 'gladiator gladiatrix' @=@ 'god godess godson goddaughter' @=@ 'governor governoress' @=@ 'granddad grandmom grandfather grandmother grandpapa grandmama' @=@ 'grandpop grandmom grandpa grandma grandpapa grandmama' @=@ 'grandnephew grandniece grandson granddaughter gramp granny' @=@ 'groom bride bridegroom bride groomsman groomswoman groomsmen groomswomen' @=@ 'guy gal' @=@ 'he she him her himself herself his her' @=@ 'headmaster headmistress' @=@ 'heir heiress' @=@ 'helmsman helmswoman helmsmen helmswomen' @=@ 'heritor heritress heritor heritrix' @=@ 'hero heroine' @=@ 'hob jill' @=@ 'horseman horsewoman horsemen horsewomen' @=@ 'host hostess' @=@ 'hunter huntress' @=@ 'husband wife husbands wives' @=@ 'incubii sucubii incubus succubus' @=@ 'inheritor inheritress inheritor inheritrix' @=@ 'instructor instructress' @=@ 'jackaroo jillaroo jack jill' @=@ 'jew jewess' @=@ 'jointer jointress' @=@ 'khaliph khalafia khaliph khalipha' @=@ 'king queen king-hit queen-hit king-of-arms queen-of-arms' @=@ 'kingcraft queencraft kingcup queencup kingdom queendom' @=@ 'kingdomful queendomful kingdomless queendomless kingdomship queendomship' @=@ 'kinged queened kinger queener kingest queenest kinghead queenhead' @=@ 'kinghood queenhood kinging queening kingless queenless' @=@ 'kinglessness queenlessness kinglier queenlier kingliest queenliest' @=@ 'kinglihood queenlihood kinglike queenlike kingliker queenliker' @=@ 'kinglikest queenlikest kingliness queenliness kingling queenling' @=@ 'kingling queenling kingly queenly kingmaker queenmaker' @=@ 'kingmaking queenmaking kingpiece queenpiece kingpin queenpin' @=@ 'kingpost queenpost kingship queenship kingside queenside' @=@ 'kingsize queensize kingsman queensman kingsmen queensmen' @=@ 'knight dame' @=@ 'lad lass laddie lassie' @=@ 'latino latina' @=@ 'landlord landlady landlords handladies landgrave landgravine' @=@ 'launderer laundress' @=@ 'lawyer layeress' @=@ 'lion lioness' @=@ 'lord lady lords ladies' @=@ 'male female maleness femaleness man woman men women manly womanly' @=@ 'manager manageress' @=@ 'manhood womenhood' @=@ 'manservant maidservant' @=@ 'margrave margavine' @=@ 'marquess marquis marquise marchioness' @=@ 'masculine feminine' @=@ 'masseue masseuse' @=@ 'mayor mayoress' @=@ 'merman mermaid' @=@ 'mediator mediatress mediator mediatrix mediator mediatrice' @=@ 'milkman milkwoman' @=@ 'millionaire millionairess billionaire billionairess' @=@ 'misandry misogyny misandrist misogynist' @=@ 'monk nun' @=@ 'monster monsteress' @=@ 'moor morisco' @=@ 'mr mrs mister missus mr ms mr mz master miss master mistress' @=@ 'murderer murderess' @=@ 'negroe negress' @=@ 'nephew niece' @=@ 'nobelman noblewoman nobelmen nobelwomen' @=@ 'orator oratress orator oratrix' @=@ 'pa ma' @=@ 'paternal maternal patriarchal matriarchal patron patroness' @=@ 'patricide matricide' @=@ 'peacock peahen' @=@ 'plowman plowwoman plowmen plowwomen' @=@ 'poet poetess' @=@ 'preacher preacheress' @=@ 'priest priestess' @=@ 'prince princess' @=@ 'prior prioress' @=@ 'proprietor proprietress' @=@ 'prophet prophetess' @=@ 'protor protectress' @=@ 'ram ewe billy ewe' @=@ 'schoolmaster schoolmistress' @=@ 'scotsman scotswoman scotsmen scotswomen' @=@ 'sculptor sculptress' @=@ 'seducer seduceress' @=@ 'seductor seductress' @=@ 'sempster sempstress' @=@ 'senor senora' @=@ 'sheepman sheepwoman sheepmen sheepwoman' @=@ 'shepherd shepherdess' @=@ 'singer singeress' @=@ 'sir madam' @=@ 'sire dam' @=@ 'son daughter' @=@ 'songster songstress' @=@ 'sorcerer sorceress' @=@ 'spokesman spokeswoman spokesmen spokeswomen' @=@ 'stag hind' @=@ 'stallion mare' @=@ 'steer heifer' @=@ 'stepdad stepmom stepfather stepmother stepson stepdaughter' @=@ 'steward stewardess' @=@ 'suitor suitress' @=@ 'sultan sultana' @=@ 'tailor seamstress' @=@ 'taskmaster taskmistress' @=@ 'temptor temptress' @=@ 'terminator terminatrix' @=@ 'toastmaster toastmistress' @=@ 'tiger tigress' @=@ 'tod vixen' @=@ 'tom hen' @=@ 'traitor traitress' @=@ 'tutor tutoress' @=@ 'tzar tzarina' @=@ 'usher usherette' @=@ 'uncle aunt' @=@ 'vampire vampiress' @=@ 'victor victress' @=@ 'villian villainess' @=@ 'viscount viscountess viscount visereine' @=@ 'vixor vixen' @=@ 'votary votaress votary votress votaries votresses' @=@ 'waiter waitress' @=@ 'warrior warrioress warlock witch' @=@ 'warder wardess' @=@ 'whoremonger whore whoremonger strumpet' @=@ 'wizard witch' @=@ 'werewolf wifwolf' @=@ 'widower widow'

say center(" There're " words(@) ' words in the gender bender list. ', sw, '─')

 do j=1  to words(@)  by 2;     n=j+1
 m  =word(@,j); f  =word(@,n); @.m=m    ; !.m=f    ; @.f  =f  ; !.f  =m
 ms =many(m)  ; fs =many(f)  ; @.ms=ms  ; !.ms=fs  ; @.fs =fs ; !.fs =ms
 mp =proper(m); fp =proper(f); @.mp=mp  ; !.mp=fp  ; @.fp =fp ; !.fp =mp
 mps=many(mp) ; fps=many(fp) ; @.mps=mps; !.mps=fps; @.fps=fps; !.fps=mps
 upper  m  f  ;                @.m=m    ; !.m=f    ; @.f  =f  ; !.f  =m
 ms =many(m)  ; fs =many(f)  ; @.ms=ms  ; !.ms=fs  ; @.fs =fs ; !.fs =ms
 end   /*j*/
              /*(above) handle lower/uppercase, capitalized, & plurals.*/

new=

       do k=1  for words(old);  new=new bendit(word(old,k));  end   /*k*/

say call tell new, ' new ' /*show a nicely parse "new" text.*/ exit /*stick a fork in it, we're done.*/

/*───────────────────────────────────TELL subroutine────────────────────*/ tell: procedure expose sw; parse arg z; z=space(z); $= say center(arg(2),sw,'─') /*display a formatted header. */

                              do until z==;   parse var z x z;   n=$ x
                              if length(n)<sw  then do; $=n; iterate; end
                              say strip($)
                              $=x
                              end   /*until*/

if strip($)\== then say $ say return

/*───────────────────────────────────BENDIT subroutine──────────────────*/ bendit: parse arg x 1 ox; if length(x)==1 then return ox @abc='abcdefghijklmnopqrstuvwxyz' parse upper var @abc @abcU pref suff; @abcU=@abc || @abcU _=verify(x, @abcU, 'M'); if _==0 then return ox if _\==0 then do; pref=left(x, _-1); x=substr(x,_); end xr=reverse(x) _=verify(xr, @abcU, 'M') if _\==0 then do; suff=reverse(left(xr, _-1)); xr=substr(xr,_); end x=reverse(xr) if \datatype(x,'M') then return ox

if @.x\== then return pref || !.x || suff if !.x\== then return pref || @.x || suff

                return pref ||   x || suff

/*───────────────────────────────────PROPER subroutine──────────────────*/ proper: arg L1 2; parse arg 2 _2; return L1 || _2

/*───────────────────────────────────MANY subroutine────────────────────*/ many: parse arg _; if right(_,1)=='s' then return _ || 'es'

                       if right(_,1)=='S'  then return _ || 'ES'
                       if datatype(_,'U')  then return _'S'
                                                return _'s'</lang>

This REXX program makes use of   LINESIZE   REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
The   LINESIZE.REX   REXX program is included here   ──►   LINESIZE.REX.
output

───────────────────────────────────── old ─────────────────────────────────────
When a new-hatched savage running wild about his native woodlands in a grass
clout, followed by the nibbling goats, as if he were a green sapling; even
then, in Queequegs ambitious soul, lurked a strong desire to see something
more of Christendom than a specimen whaler or two. His father was a High
Chief, a King; his uncle a High Priest; and on the maternal side he boasted
aunts who were the wives of unconquerable warriors. There was excellent blood
in his veins-royal stuff; though sadly vitiated, I fear, by the cannibal
propensity he nourished in his untutored youth.

─────────────── There're  660  words in the gender bender list. ───────────────

───────────────────────────────────── new ─────────────────────────────────────
When a new-hatched savage running wild about her native woodlands in a grass
clout, followed by the nibbling goats, as if she were a green sapling; even
then, in Queequegs ambitious soul, lurked a strong desire to see something
more of Christendom than a specimen whaler or two. Her mother was a High
Chiefess, a Queen; her aunt a High Priestess; and on the paternal side she
boasted uncles who were the husbands of unconquerable warrioresses. There was
excellent blood in her veins-royal stuff; though sadly vitiated, I fear, by
the cannibal propensity she nourished in her untutored youth.

Sidef

<lang ruby>var male2female = <<'EOD'

 maleS femaleS, maleness femaleness, him her, himself herself, his her, his
 hers, he she, Mr Mrs, Mister Missus, Ms Mr, Master Miss, MasterS MistressES,
 uncleS auntS, nephewS nieceS, sonS daughterS, grandsonS granddaughterS,
 brotherS sisterS, man woman, men women, boyS girlS, paternal maternal,
 grandfatherS grandmotherS, GodfatherS GodmotherS, GodsonS GoddaughterS,
 fiancéS fiancéeS, husband wife, husbands wives, fatherS motherS, bachelorS
 spinsterS, bridegroomS brideS, widowerS widowS, KnightS DameS, Sir DameS,
 KingS QueenS, DukeS DuchessES, PrinceS PrincessES, Lord Lady, Lords Ladies,
 MarquessES MarchionessES, EarlS CountessES, ViscountS ViscountessES, ladS
 lassES, sir madam, gentleman lady, gentlemen ladies, BaronS BaronessES,
 stallionS mareS, ramS eweS, coltS fillieS, billy nanny, billies nannies,
 bullS cowS, godS goddessES, heroS heroineS, shirtS blouseS, undies nickers,
 sweat glow, jackarooS jillarooS, gigoloS hookerS, landlord landlady,
 landlords landladies, manservantS maidservantS, actorS actressES, CountS
 CountessES, EmperorS EmpressES, giantS giantessES, heirS heiressES, hostS
 hostessES, lionS lionessES, managerS manageressES, murdererS murderessES,
 priestS priestessES, poetS poetessES, shepherdS shepherdessES, stewardS
 stewardessES, tigerS tigressES, waiterS waitressES, cockS henS, dogS bitchES,
 drakeS henS, dogS vixenS, tomS tibS, boarS sowS, buckS roeS, peacockS
 peahenS, gander goose, ganders geese, friarS nunS, monkS nunS

EOD   var m2f = male2female.split(/,\s*/).map { |tok| tok.words}   var re_plural = /E?S\z/ var re_ES = /ES\z/   func gen_pluralize(m, f) {

   [
       [m - re_plural, f - re_plural],
       [m.sub(re_ES, 'es'), f.sub(re_ES, 'es')],
       [m.sub(re_plural, 's'), f.sub(re_plural, 's')],
   ]

}   var dict = Hash()   for m,f in m2f {

   for x,y in gen_pluralize(m, f).map{.map{.lc}} {
       if (x ~~ dict) {
           dict{y} = x
       } else {
           dict{x, y} = (y, x)
       }
   }

}   var gen_re = Regex.new('\b(' + dict.keys.join('|') + ')\b', 'i')   func copy_case(orig, repl) {

   var a = orig.chars
   var b = repl.chars

 

   var uc = 0
   var min = [a, b].map{.len}.min
   for i in ^min {
       if (a[i] ~~ /^upper:/) {
           b[i].uc!
           ++uc
       }
   }

 

   uc == min ? repl.uc : b.join()

}   func reverse_gender(text) {

   text.gsub(gen_re, { |a| copy_case(a, dict{a.lc}) })

}</lang>

Example: <lang ruby>say reverse_gender("She was a soul stripper. She took my heart!");</lang>

Output:
He was a soul stripper. He took my heart!

Tcl

<lang tcl># Construct the mapping variables from the source mapping apply {{} {

   global genderMap genderRE
   # The mapping is from the Python solution, though omitting the names
   # for the sake of a bit of brevity...
   foreach {maleTerm femaleTerm} {

maleS femaleS maleness femaleness him her himself herself his hers his her he she Mr Mrs Mister Missus Ms Mr Master Miss Master Mistress uncleS auntS nephewS nieceS sonS daughterS grandsonS granddaughterS brotherS sisterS man woman men women boyS girlS paternal maternal grandfatherS grandmotherS GodfatherS GodmotherS GodsonS GoddaughterS fiancéS fiancéeS husband wife husbands wives fatherS motherS bachelorS spinsterS bridegroomS brideS widowerS widowS KnightS DameS Sir DameS KingS QueenS DukeS DuchessES PrinceS PrincessES Lord Lady Lords Ladies MarquessES MarchionessES EarlS CountessES ViscountS ViscountessES ladS lassES sir madam gentleman lady gentlemen ladies BaronS BaronessES stallionS mareS ramS eweS coltS fillieS billy nanny billies nannies bullS cowS godS goddessES heroS heroineS shirtS blouseS undies nickers sweat glow jackarooS jillarooS gigoloS hookerS landlord landlady landlords landladies manservantS maidservantS actorS actressES CountS CountessES EmperorS EmpressES giantS giantessES heirS heiressES hostS hostessES lionS lionessES managerS manageressES murdererS murderessES priestS priestessES poetS poetessES shepherdS shepherdessES stewardS stewardessES tigerS tigressES waiterS waitressES cockS henS dogS bitchES drakeS henS dogS vixenS tomS tibS boarS sowS buckS roeS peacockS peahenS gander goose ganders geese friarS nunS monkS nunS

   } {

foreach {m f} [list \ $maleTerm $femaleTerm \ [regsub {E*S$} $maleTerm ""] [regsub {E*S$} $femaleTerm ""] ] { dict set genderMap [string tolower $m] [string tolower $f] dict set genderMap [string toupper $m] [string toupper $f] dict set genderMap [string totitle $m] [string totitle $f] dict set genderMap [string tolower $f] [string tolower $m] dict set genderMap [string toupper $f] [string toupper $m] dict set genderMap [string totitle $f] [string totitle $m] }

   }
   # Now the RE, which matches any key in the map *as a word*
   set genderRE "\\m(?:[join [dict keys $genderMap] |])\\M"

}}

proc reverseGender {string} {

   global genderRE genderMap
   # Used to disable Tcl's metacharacters for [subst]
   set safetyMap {\\ \\\\ \[ \\\[ \] \\\] $ \\$}
   subst [regsub -all $genderRE [string map $safetyMap $string] {[

string map $genderMap &

   ]}]

}</lang> Demonstrating: <lang tcl>puts [reverseGender "She was a soul stripper. She took my heart!"]\n puts [reverseGender "When a new-hatched savage running wild about his native woodlands in a grass clout, followed by the nibbling goats, as if he were a green sapling; even then, in Queequeg's ambitious soul, lurked a strong desire to see something more of Christendom than a specimen whaler or two. His father was a High Chief, a King; his uncle a High Priest; and on the maternal side he boasted aunts who were the wives of unconquerable warriors. There was excellent blood in his veins-royal stuff; though sadly vitiated, I fear, by the cannibal propensity he nourished in his untutored youth."]</lang>

Output:
He was a soul stripper. He took my heart!

When a new-hatched savage running wild about her native
woodlands in a grass clout, followed by the nibbling goats, as if
she were a green sapling; even then, in Queequeg's ambitious soul,
lurked a strong desire to see something more of Christendom than
a specimen whaler or two. Her mother was a High Chief, a Queen;
her aunt a High Priestess; and on the paternal side she boasted uncles
who were the husbands of unconquerable warriors. There was excellent
blood in her veins-royal stuff; though sadly vitiated, I fear,
by the cannibal propensity she nourished in her untutored youth.

Go

<lang Go> package main

import "fmt" import "strings" func main() { s := "She was a soul stripper. She took my heart!" fmt.Println(s)

if strings.Contains(s, "She") { y:= strings.Replace(s, "She ", " He ", -1) fmt.Println(y) }else if strings.Contains(s, "He") { y:= strings.Replace(s, "He ", " She ", -1) fmt.Println(y) } } </lang>

Output:
She was a  soul stripper. She took  my heart!
 He was a  soul stripper.  He took  my heart!