0
对于Python中的基本计算机科学类,我们正在编写一个程序读入文件,将文件翻译成猪拉丁文,并将翻译写入新文件,并计算翻译的行数和单词数。如何分成两个功能?
file_path = raw_input("Enter a file pathway: ")
f_input = file(file_path, "r")
f_output = file("pig_output.txt","w")
vowels = ("a","e","i","o","u","A","E","I","O","U")
def piglat_trans():
line_count = 0
word_count = 0
for line in f_input:
words = line.split(" ")
pig_line = ""
line_count += 1
for word in words:
word = word.strip("\n")
word_count += 1
if word[0] in vowels:
pig_word = word + "way"
elif word[0] not in vowels and word[1] not in vowels and len(word)>1:
pig_word = word [2:len(word)] + word[0] + word[1] + "ay"
else:
pig_word = word[1:len(word)] + word[0] + "ay"
pig_line += pig_word + " "
f_output.write(pig_line + "\n")
print "Translation finished and written pig_output.txt"
print "A total of " + str(line_count) + " lines were translated successfully."
print "A total of " + str(word_count) + " words were translated successfully."
piglat_trans()
f_input.close()
f_output.close()
该程序工作正常,但我应该让行/字数和打印部分将功能与翻译器本身分开。我将如何做到这一点?
感谢您的帮助! **编辑:我也一直有与空格和制表符与翻译问题,它返回:
line 25, in piglat_trans if word[0] in vowels:
IndexError: string index out of range
在过去的错误,认为''一b'.split(”“)'将返回'[‘一’,‘’,“B “]';你可能想要没有参数的'.split()'。 – o11c 2014-11-07 00:33:41