PaulB1234 PaulB1234 - 7 months ago 9
Python Question

Python 2.7 - Program only using one line out of x amount

I'm currently trying to get my program to accept multiple lines, but at the moment it's picking the last line, and just converting that to pig latin. I believe it's this part of the code, but I don't know exactly what to change.

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)


The complete code is:

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



# Functions

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
text = raw_input("Enter the path of a text file: ")
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"


The input file contains:

Pig latin
I dont know what is wrong with this
Random testing
Randomly typing


Output file is:

andomlyRay ypingtay

Answer

In your code there are several inconsistencies and weird constructs; just looking at the most obvious issues, change your pig_word as:

def pig_word(string):
    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" + " "
            lines.append(new_string)
    return lines

then at the bottom of the script, where you save the output:

out_file.write('\n'.join(pig))

There would be other things to discuss on your code, but this should fix the biggest issue.