猪拉丁语翻译

时间:2014-03-31 23:00:23

标签: python if-statement while-loop

所以,我有一个基本的Pig Latin翻译器,只适用于一个单词。

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"

有人可以帮我编辑这个翻译器以获取多个单词吗?谢谢。

3 个答案:

答案 0 :(得分:3)

这里的猪拉丁语方言考虑了单词的发音方式:

#!/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))

输出

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

注意:

  • "-way"后缀用于以元音开头的单词
  • qu in" quiet"被视为一个单位
  • Europeanunit以辅音开头
  • y in"节奏","王朝"是一个元音
  • nthhourherbheir以元音开头

其中to_piglatin()是:

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

要将文本拆分为句子,可以使用nltk标记符。可以修改代码以尊重字母' case(大写/小写),收缩。

答案 1 :(得分:1)

如果函数实现了一个小的任务,那么函数最有用,所以我会保持你当前的函数或多或少(通过一些样式修复):

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"

然后编写一个额外的函数,使用该单个单词函数翻译整个句子:

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

示例:

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

答案 2 :(得分:0)

只是为了好玩,这是一个使用re.split的非常易读的Python3版本:

>>> 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'

示例用法:

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