Tradutor De Latim De Porco

Então, eu tenho um tradutor básico de latim de porco que só funciona para uma palavra.

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"
Alguém pode ajudar-me a editar este tradutor para levar mais do que uma palavra? Obrigado.

Author: Tahmoor Cyan, 2014-04-01

3 answers

Aqui está o dialeto suco latino que leva em conta como as palavras são pronunciadas:
#!/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))

Resultado

"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."

Nota:

  • "-way" o sufixo é usado para palavras que começam com um som vocálico
  • qu em "silêncio" é tratado como uma unidade
  • European, unit Comece com uma consoante
  • Em "ritmos", "dinastia" é uma vogal.
  • nth, hour, herb, heir iniciar com uma vogal

Onde to_piglatin() riz:

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()

Para dividir o texto em frases, palavras que você poderia usar nltk tokenizers. É possível modificar o código para respeitar a maiúscula (maiúsculas/minúsculas), contrações.

 3
Author: jfs, 2014-04-01 04:06:19

As funções são mais úteis se alcançarem uma única tarefa pequena, por isso eu deixaria a sua função actual mais ou menos como está (com algumas correcções de estilo):

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"

E depois escrever uma função extra que usa essa única função de palavra para traduzir uma frase inteira:

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

Exemplo:

s1 = "Pig latin is fun"
translate_sentence(s1)
Out[12]: 'igPay atinlay isay unfay'
 1
Author: Marius, 2014-03-31 23:21:31

Só para os funzies aqui está uma versão Python3 bastante legível usando 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'

E uso de exemplo:

>>> phrase = 'The quick brown fox jumps over the lazy dog'
>>> ' '.join(pig_latin(phrase))
'eThay uickqay ownbray oxfay umpsjay overyay ethay azylay ogday'
 0
Author: Two-Bit Alchemist, 2014-03-31 23:38:26