【发布时间】:2020-11-17 23:57:43
【问题描述】:
我正在尝试制作 Pig Latin 翻译器,但我的代码出现问题,当输入诸如“hi”或 /chair/ 之类的词时,它无法正常工作。这是因为我需要我的代码来检测输入是否包含非字母字符,将其从字符串中取出,并在完成更改字符串后将其放回。不过,我正在努力做到这一点。
# Pig Latin 11/11/20
#!/usr/bin/env python3
vowels = ("A", "E", "I", "O", "U")
message = input("Input text to be translated to Pig
Latin\n")
message = message.split()
not_alpha = {}
new_message = []
for word in message:
这个被注释掉的部分是我试图解决这个问题的地方,在单词通过编辑过程之前,它会通过这里并删除 non_alpha 键并将它们放在一个名为 not_alpha 的字典中。我的想法是,我将它放在字典中,以字符为键,以字符串中的索引为值。然后,最后,我将遍历单词中的每个字母,并按顺序使用所有非字母字符重构单词。
# for letter in word:
# if not letter.isalpha():
# not_alpha[letter] = word.index(letter)
# word = word
# for k in not_alpha.keys():
# word.replace(k, "")
letter_editing = word[0]
if word.isalpha():
if letter_editing.upper() in vowels:
word += "yay"
else:
letter_editing = word[0:2]
if letter_editing.upper() in vowels:
word = word[1:] + word[0] + "ay"
else:
word = word[2:] + word[0:2] + "ay"
# for letter in word:
# if word.index(letter) in not_alpha.values():
【问题讨论】:
-
我认为你把这个过程复杂化了。虽然我不知道您对猪拉丁语转换的确切规则,但它们通常类似于:
标签: python python-3.x dictionary