Python 2.7 - 通过txt文件接受多行

时间:2016-04-16 19:30:50

标签: python python-2.7

有人给了我这个代码试图修复,(猪拉丁语)我已经通过txt文件接受了一行,但是当我在txt文件中添加更多行时它会中断。有索引错误。你们谁都知道我的问题是什么?

vowels = ("A", "a", "E", "e", "I", "i", "O", "o", "U", "u")



# Functions

text = raw_input("Enter the path of a text file: ")
def pig_word(string):
    for line in text:
        line = line.split()
    lines = []
    for line in string.split('\n'):
        new_string = ""
        for word in line.split(" "):
            first_letter = word[0]
            if first_letter in vowels:
                 new_string += word + "way" + " "
            else:
                 new_string += word[1:] + first_letter + "ay" + " "
                 global new_string
            lines.append(new_string)



def line_counter(s):
    line_count = 0
    for _ in s.split("\n"):
        line_count += 1
    return line_count

def word_counter(line):
    word_count = 0
    list_of_words = line.split()
    word_count += len(list_of_words)
    return word_count

# File path conversion

file_path = open(text, "r")
out_file = open("pig_output.txt", "w")


s = file_path.read()
pig = pig_word(s)
out_file.write(str(new_string)+ "\n")
out_file.write("\n")


linecount = line_counter(s)
wordcount = word_counter(s)


file_path.close()
out_file.close()

# Results

print "\n\n\n\nTranslation finished and written to pig_output.txt"
print "A total of {} lines were translated successfully.".format(linecount)
print "A total of {} words were translated successfully.".format(wordcount)
print "\n\n\n\n"

错误是:

    Traceback (most recent call last):
  File "C:/Users/Administrator.MU-L-ZB046882H/Desktop/Code/chal.py", line 42, in <module>
    pig = pig_word(s)
  File "C:/Users/Administrator.MU-L-ZB046882H/Desktop/Code/chal.py", line 13, in pig_word
    first_letter = word[0]
IndexError: string index out of range
>>> 

2 个答案:

答案 0 :(得分:0)

'new_string + = word [1:] + first_letter +“ay”+“”' 如果单词只有一个字母如'a';)

,则该行可以执行超出范围异常的索引

我同意你的全球声明令人困惑和错误来源的评论 - 只是建议更好的风格;)

答案 1 :(得分:0)

错误显示您正尝试访问空字符串中的第一个字母。

案例可能是您使用.split明确使用" "

如果你举一个空格很少的行并将其拆分为" ",你会得到几个空字符串:

>>> line = "     "
>>> line.split(" ")
['', '', '', '', '', '']

您可能最好使用默认空白空格分隔符进行拆分:

>>> line.split()
[]