Tahmoor Cyan
Tahmoor Cyan

Reputation: 129

Pig Latin Translator

So, I have a basic Pig Latin translator that only works for one word.

def Translate(Phrase):
Subscript = 0

while Phrase[Subscript] != "a" or Phrase[Subscript] != "e" or Phrase[Subscript] != "i" or           
  Phrase[Subscript] != "o" or Phrase[Subscript] != "u":  

  Subscript += 1
if Phrase[Subscript] == "a" or Phrase[Subscript] == "e" or Phrase[Subscript] == "i" or   

Phrase[Subscript] == "o" or Phrase[Subscript] == "u":  
return Phrase[Subscript:] + Phrase[:Subscript] + "ay"

Can someone please assist me in editing this translator in order to take more than one word? Thank you.

Upvotes: 0

Views: 3662

Answers (3)

jfs
jfs

Reputation: 414315

Here's pig latin dialect that takes into account how the words are pronounced:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

sentences = ["Pig qoph an egg.",
             "Quiet European rhythms.",
             "My nth happy hour.",
             "Herb unit -- a dynasty heir."]
for sent in sentences:
    entsay = " ".join(["".join(map(to_piglatin, re.split("(\W+)", nonws)))
                       for nonws in sent.split()])
    print(u'"{}" → "{}"'.format(sent, entsay))

Output

"Pig qoph an egg." → "igpay ophqay anway eggway."
"Quiet European rhythms." → "ietquay uropeaneay ythmsrhay."
"My nth happy hour." → "ymay nthway appyhay hourway."
"Herb unit -- a dynasty heir." → "herbway itunay -- away ynastyday heirway."

Note:

  • "-way" suffix is used for words that start with a vowel sound
  • qu in "quiet" is treated as a unit
  • European, unit start with a consonant
  • y in "rhythms", "dynasty" is a vowel
  • nth, hour, herb, heir start with a vowel

where to_piglatin() is:

from nltk.corpus import cmudict # $ pip install nltk
# $ python -c "import nltk; nltk.download('cmudict')"

def to_piglatin(word, pronunciations=cmudict.dict()):
    word = word.lower() #NOTE: ignore Unicode casefold
    i = 0
    # find out whether the word start with a vowel sound using
    # the pronunciations dictionary
    for syllables in pronunciations.get(word, []):
        for i, syl in enumerate(syllables):
            isvowel = syl[-1].isdigit()
            if isvowel:
                break
        else: # no vowels
            assert 0
        if i == 0: # starts with a vowel
            return word + "way"
        elif "y" in word: # allow 'y' as a vowel for known words
            return to_piglatin_naive(word, vowels="aeiouy", start=i)
        break # use only the first pronunciation
    return to_piglatin_naive(word, start=i)

def to_piglatin_naive(word, vowels="aeiou", start=0):
    word = word.lower()
    i = 0
    for i, c in enumerate(word[start:], start=start):
        if c in vowels:
            break
    else: # no vowel in the word
        i += 1
    return word[i:] + word[:i] + "w"*(i == 0) + "ay"*word.isalnum()

To split the text into sentences, words you could use nltk tokenizers. It is possible to modify the code to respect letters' case (uppercase/lowercase), contractions.

Upvotes: 3

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18467

Just for funzies here's a pretty readable Python3 version using re.split:

>>> import re
>>> def pig_latin(sentence):
...   vowels = re.compile('|'.join('aeiouAEIOU'))
...   for word in sentence.split():
...     first_syl = re.split(vowels, word)[0]
...     if first_syl:
...       yield word[len(first_syl):] + first_syl + 'ay'
...     else:
...       yield word + 'yay'

And example usage:

>>> phrase = 'The quick brown fox jumps over the lazy dog'
>>> ' '.join(pig_latin(phrase))
'eThay uickqay ownbray oxfay umpsjay overyay ethay azylay ogday'

Upvotes: 0

Marius
Marius

Reputation: 60080

Functions are most useful if they achieve a single, small task, so I would leave your current function more or less as is (with a few style fixes):

def translate(word):
    subscript = 0
    while word[subscript] not in ("a", "e", "i", "o", "u"):
        subscript +=1
    if word[subscript] in ("a", "e", "i", "o", "u"):
        return word[subscript:] + word[:subscript] + "ay"

And then write an extra function that uses that single word function to translate a whole sentence:

def translate_sentence(sentence):
    words = sentence.split()
    pigged = []
    for word in words:
        pigged_word = translate(word)
        pigged.append(pigged_word)
    # Turn it back into a single string
    result = " ".join(pigged)
    return result

Example:

s1 = "Pig latin is fun"
translate_sentence(s1)
Out[12]: 'igPay atinlay isay unfay'

Upvotes: 1

Related Questions