如何将文本文件中的单词翻译成猪拉丁语
通过使用'for'循环,我把文本文件里的内容分解成了列表,像这样:
['these', 'are', 'lines']
['meant', 'to', 'be', 'translated']
['to', 'piglatin']
简单来说,如果单词以元音字母'a、e、i、o、u'开头,就在后面加上'yay';如果不是,就把字母移动到后面,直到找到一个元音字母,然后再加'yay'。如果单词里没有元音字母,就不处理它。
举个例子;要翻译的单词'about',结果会是:aboutyay,'to'会变成'otay','be'变成'ebay','translated'变成'anslatedtray'。
这是我目前的代码:
untranslated = open('english.txt','r')
vowels = 'aeiou'
for lines in untranslated:
words = lines.split()
print(words)
我不想要完整的代码,只想知道怎么开始处理第一个单词,以及如何切分它。
1 个回答
0
如何切割一个字符串:
word = 'these'
print word[0] # it's similar to list indexing, starts at 0
如果你想把字母倒过来读,可以用负数来实现:word[-1]
是最后一个字母;word[-2]
是倒数第二个字母,依此类推。
word[1:]
会返回从索引1(第二个字母)开始到最后的所有字母。word[:5]
会返回从开头到索引5之前的所有字母(也就是字母1、2、3和4)。word[1:5]
会返回从索引1到索引5之前的所有字母(也就是字母2、3和4)。
因为你有多行内容,所以你想用 words += lines.split()
来处理。
untranslated = open('english.txt','r')
vowels = ('a', 'e', 'i', 'o', 'u') # I like using lists/tuples rather than strings
# if you are just checking if something is in it
newWords = []
for lines in untranslated:
words += lines.split() # this fixes the last line problem
# this assumes each word is on one line, separated by a space (like: 'these are words')
for word in words: # iterates through every word
if word[0] in vowels: # if first letter is a vowel
new_word = word + 'yay'
else:
new_word = word[1:] + word[0] + 'ay'
newWords.apend(new_word)
根据Eric Roper的建议,你可以创建一个字典来进行翻译:
newWords = {}
for word in words:
if word[0] in vowels:
new_word = word + 'yay'
newWords[word] = new_word
else:
new_word = word[1:] + word[0] + 'ay'
newWords[word] = new_word
一些参考资料: