如何解决Pig Latin翻译
这是Pig Latin方言,考虑了单词的发音方式:
#!/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))
输出量
“猪qoph一个鸡蛋。” →“ igpay ophqay anway鸡蛋路。”
“安静的欧洲节奏。” →“ ietquay uropeaneay ythmsrhay。”
“我的第n个欢乐时光。” →“ ymay nthway appyhay小时制。”
“草药单位-王朝继承人。” →“草帽itunay-离开ynastyday继承人”。
注意:
-
"-way"
后缀用于以元音开头的单词 -
qu
在“安静”中被视为一个单位 -
European
,unit
从辅音开始 -
y
在“节奏”中,“王朝”是元音 -
nth
,hour
,herb
,heir
开始以元音
在哪里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
标记符来分隔单词。可以修改代码以尊重字母的大小写(大写/小写),紧缩。
解决方法
因此,我有一个基本的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"
有人可以协助我编辑此翻译器以使用多个单词吗?谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。