import string
def main():
filename = input("Enter the name of a file to translate into Pig Latin: ")
vowels = ['a', 'e', 'i', 'o', 'u','A','E','I','O','U']
regFile = open((filename), 'r')
Output = open('Output.txt', 'w')
for line in regFile.readlines():
pigList = line.split()
t = translate(pigList, vowels)
w = write(t, Output)
regFile.close()
input ("Press ENTER to continue: ")
def translate(pigList, vowels):
PigList2 = []
for word in pigList:
if word[-1] in string.punctuation:
actual_word = word[:-1]
ending = word[-1]
else:
actual_word = word
ending = ""
if word[0] in vowels:
PigList2.append(actual_word + "-yay" + ending)
else:
PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
return PigList2
def write(pigList, Output):
print(" ".join(pigList))
main()
I believe this has fixed my errors. Thank you for the help. I know have the translator working correctly and translating all the lines at once instead of one line at a time.
You're almost there. I just used used the punctuation check to split up your word into the actual word and the punctuation and then append the '-' before the first letter rather than with the "ay".
def translate(pigList, vowels):
PigList2 = []
for word in pigList:
if word[-1] in string.punctuation:
actual_word = word[:-1]
ending = word[-1]
else:
actual_word = word
ending = ""
if word[0] in vowels:
PigList2.append(actual_word + "-yay" + ending)
else:
PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
return PigList2
Related
I am trying to pass words to a function that will be checked with words in a seperate file. It only passes the last word created from the first file and not each word. So I think how it should work is as soon as it creates a word it should pass that word to the function then check it and return the results, but I'm confused as to how. If the word matches a word in the second file it should print the word then a 0 or if it doesn't match a word then print 1.
import sys
argc = len(sys.argv)
cmdlength = argc - 1
if cmdlength != 2:
print ("Usage error, expected 2 args got " + str(cmdlength))
exit()
else:
word = ""
with open(sys.argv[1],"r") as fh:
while True:
ch=fh.read(1)
if not ch:
print(word)
print("End of file")
break
if ch == ' ':
print(word)
word = ''
else:
word += ch
def check_word(word):
count = 0
count2 = 0
with open(sys.argv[2],"r") as fh2:
lines = fh2.readlines()
for line in lines:
if word in line:
print(word , ": " , "0")
count += 1
else:
print(word, ": " , "1")
count += 1
check_word(word)
When you call the check_word function, you are doing it once after the while loop ends, for that reason only the last word is passed to the function. You should call the function after each word is armed, in your case, when ch == ' ':
if ch == ' ':
print(word)
check_word(word)
word = ''
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
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.
You use the global variable new_string to print out the result. This variable contains only one line, therefore, at the end of the for-loop, the last line. Return the variable lines, which is at the moment unused, and use this list to print out every line:
def pig_word(string):
lines = []
for line in string.split('\n'):
new_line = []
for word in line.split():
first_letter = word[0]
if first_letter in vowels:
new_line.append(word + "way")
else:
new_line.append(word[1:] + first_letter)
lines.append(' '.join(new_line))
return lines
I'm making a program that finds every word in a block of text and outputs each word and how many times the word was used.
My current code is here:
text = input("Please enter some text ")
terminator = len(text)
n = 0
word = ""
wordlist = []
while len(text) > 0:
if word != "":
wordlist.append(word)
text = text[n:]
word = ""
n = 0
for char in text:
if char != " ":
word = word + char
n = n + 1
else:
text = text[1:]
break
for item in wordlist:
print(item)
thanks :)
I'd do something like this:
import re
from collections import Counter
text = input("Please enter some text ")
text = re.sub(' +', ' ', text)
text = text.split(' ')
counter = Counter(text)
The line text = re.sub(' +', ' ', text) deals with cases where the user enters multiple consecutive spaces.
For a basic computer science class in python we're writing a program that reads in a file, translates the file to pig latin and writes the translation in a new file, and counts the number of lines and words translated.
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()
The program works fine, but I'm supposed to make the line/word count and the printing parts separate functions from the translator itself. How would I do this?
Thanks for the help!
** Edit: also I've been having a problem with spaces and tabs with the translation and it returns:
line 25, in piglat_trans if word[0] in vowels:
IndexError: string index out of range
Well, since this is a homework, I won't write code.
Looks like your key logic lies in the most inner for-loop, where you take a word and pig_latinify it.
And after that, you just need a mapper function for mapping every word of the source to a pig-latinified version of the text. This function can also count the number of lines.
And, try to make your file handlers short lived, and use a context manager(with statement in Python).
Here is what I'd do:
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
I need to separate words that have at least one uppercase letter with the lowercase. I need to take input and separate uppercase words and lowercase words and print them both. Here is my code:
text = input("Input your text: ")
words0 = text.strip().split()
words1 = []
words2 = []
wordslen= len(words0)
for word in words0:
counter = 0
for x in word:
while counter != wordslen:
if x.isupper():
words1.append(word)
else:
words2.append(word)
counter += 1
wordsupper = list(set(words1))
wordslower = list(set(words2))
allwords = wordsupper + wordslower
for word in allwords:
print(word)
words = input("Input your text: ").strip().split()
lower, mixed = set(), set()
for word in words:
if word == word.lower():
lower.add(word)
else:
mixed.add(word)
print("Lowercase words: " + ", ".join(lower))
print("Mixed- and uppercase words: " + ", ".join(mixed))
which runs like:
Input your text: This is a Perl and Python party.
Lowercase words: a, and, is, party.
Mixed- and uppercase words: This, Python, Perl
To separate words that have only lowercase characters from the rest:
text = raw_input('Input text: ')
lower, rest = set(), set()
for word in text.split():
(lower if word == word.lower() else rest).add(word)
print(lower)
print(rest)
this is similar to previous posts, but uses map() instead of for word in words:
text = raw_input("Input your text: ")
words = text.strip().split()
upper = []
lower = []
def sort_word(word):
if word.lower() == word:
lower.append(word)
else:
upper.append(word)
map(sort_word, words)
Maybe something like this:
text = input("Input your text: ")
words = text.strip().split()
wordslower = []
wordsupper = []
for word in words:
# if the word is the same as word.lower() that means all the
# characters are lower case. Also, don't add duplicates to
# the list.
if word == word.lower():
if word not in wordslower:
wordslower.append(word)
else: # The word has at least one capital letter
if word not in wordsupper:
wordsupper.append(word)
print(wordslower)
print(wordsupper)
Try this:
def check(word):
for k in word:
if k != k.lower(): #If the letter is capitalized
return True
return False
text = input('Text: ')
text = text.strip().split()
wordsupper = []
wordslower = []
for k in text:
if check(k) == True:
wordsupper.append(k)
else:
wordslower.append(k)
print(wordslower)
print(wordsupper)