Python字符串和Piglatin

2024-10-01 07:42:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

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函数向用户请求文件名以将其转换为pigltin?在


Tags: stringindexreturnifdefelsefilecharacter
1条回答
网友
1楼 · 发布于 2024-10-01 07:42:35
# 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!"

相关问题 更多 >