1

因此,通过使用“for”语句,我将文本文件分解为列表,如下所示:

['these', 'are', 'lines']
['meant', 'to', 'be', 'translated']
['to', 'piglatin']

所以基本上如果它以元音'aeiou'开头,你就拿这个词+'yay',如果它没有你把字母移到后面直到你到达一个元音然后加yay,如果它没有元音你忽略它。

例如; 即将翻译,将是:aboutyay otay ebay anslatedtray。

到目前为止,这是我的代码:

untranslated = open('english.txt','r')
vowels = 'aeiou'


for lines in untranslated:
    words = lines.split()
    print(words)

我不想要关于如何完成这个或多或少的完整代码,我将如何从第一个单词开始以及如何拼接它。

4

1 回答 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] returns every letter up to index 5 (exclusive, letters 1, 2, 3, and 4). words[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

一些参考资料:

于 2013-02-23T00:39:00.020 回答