2014-11-07 64 views
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 
+0

在过去的错误,认为''一b'.split(”“)'将返回'[‘一’,‘’,“B “]';你可能想要没有参数的'.split()'。 – o11c 2014-11-07 00:33:41

回答

0

好,因为这是一门功课,我不会写代码。

看起来你的关键逻辑在于最内在的循环,在那里你写一个词并将它弄糊涂。

之后,您只需要一个映射器函数,将源的每个单词映射到文本的猪拉丁语版本。该功能还可以计算行数。

然后,尝试使您的文件处理程序寿命短,并使用上下文管理器(Python中的with语句)。

这里是我会怎么做:

def pigify(word): 
    .... 
    return pig 

def pigify_text(text): 
    ... 
    pig_words = map(pigify, words) 
    ... 
    return (pig_text, word_count, line_count) 

with open(infile) as f: 
    text = f.read() 

pig, wc, lc = pigify_text(text) 

with open(outfield, "w") as f: 
    f.write(pig) 

print wc 
print lc