Python字符串和Piglatin

时间:2014-02-22 18:06:40

标签: python string

我的代码:

def isVowel(character):
    vowels = 'aeiouAEIOU'
    return character in vowels

def toPigLatin(String):
    index = 0
    stringLength = len(String)
    consonants = ''

    if isVowel(String[index]): 
        return String + '-ay' 
    else:
        consonants += String[index]
        index += 1
        while index < stringLength:
            if isVowel(String[index]):
                return String[index:stringLength] + '-' +consonants + 'ay'
            else:
                consonants += String[index]
                index += 1
        return 'This word does contain any vowels.'

def printAsPigLatin(file):
    return toPigLatin(file)

该程序必须要求文件名将其转换为piglatin。该文件每行包含一个单词。如何使用我的printAsPigLatin函数向用户询问文件名以将其转换为piglatin?

1 个答案:

答案 0 :(得分:1)

# grab input file name from user
read = raw_input("Input filename? ")

# grab output file name from user
write = raw_input("Output filename? ")

# open the files, assign objects to variables
readfile = open(read, "r")
writefile = open(write, "w")

# read each line from input file into list "lines"
lines = readfile.readlines()

# for each line in lines, translate the line and write it to the output file
for line in lines:
    line = toPigLatin(line.strip("\n"))
    writefile.write(line + "\n")

# we're done, close our files!
readfile.close()
writefile.close()
print "Done!"