# Reading line of text
text = input("Enter text: ")
print("English: " ,text)
# Removing punctuation
text = removePunctuation(text)
# Converting to lower case
text = text.lower()
# Iterating over words
for word in text.split(" "):
# Converting word to Pig Latin form
word = pigLatin(word)
# Printing word
print(word, end = " ");
How can I get it to say Pig: and then the Pig Latin form? Every time i try this, it just adds the Pig Latin transformation to the previous word.
You're trying to make one variable do two things at once.
If you want to use the old value later (in your print) then quit destroying the original value:
pl_word = pigLatin(word)
print (word, pl_word)
print("Pig:", word)
Next time, please use capital letters and some markdown... https://stackoverflow.com/editing-help
Related
I coded this in order to get a list full of a given string words .
data=str(input("string"))
L=[]
word=""
for i in data:
if i.isalpha() :
word+=i
elif :
L.append(word)
word=""
but, when I run this code it doesn't show the last word !
You can simply split words on a string using str.split() method, here is a demo:
data = input("string: ")
words = data.split()
L = []
for word in words:
if word.isalpha():
L.append(word)
print(L)
Note that .split() splits a string by any whitespace character by default, if you want for example to split using commas instead, you can simply use data.split(",").
You are not getting the last word into the list because it does not have non-alpha character to make it pass to the else stage and save the word to list.
Let's correct your code a little. I assume you want to check the words in the string but not characters(because what you are doing right now is checking each charackter not words.):
data=input("Input the string: ") #you don't need to cast string to string (input() returns string)
data = data+' ' # to make it save the last word
l=[] #variable names should be lowercase
word=""
for i in data:
if i.isalpha() :
word+=i
else: # you shouldn't use elif it is else if no condition is provided
l.append(word)
word=" " # not to make each word connected right after each other
This is the question I was given to solve:
Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z.
I solved the problem, but the first two methods didn't work and I wanted to know why:
#1 string index out of range
quote = input("enter a 1 sentence quote, non-alpha separate words: ")
word = ""
for character in quote:
if character.isalpha():
word += character.upper()
else:
if word[0].lower() >= "h":
print(word)
word = ""
else:
word = ""
I get the IndexError: string index out of range message for any words after "g". Shouldn't the else statement catch it? I don't get why it doesn't, because if I remove the brackets [] from word[0], it works.
#2: last word not printing
quote = input("enter a 1 sentence quote, non-alpha separate words: ")
word = ""
for character in quote:
if character.isalpha():
word += character.upper()
else:
if word.lower() >= "h":
print(word)
word = ""
else:
word = ""
In this example, it works to a degree. It eliminates any words before 'h' and prints words after 'h', but for some reason doesn't print the last word. It doesn't matter what quote i use, it doesn't print the last word even if it's after 'h'. Why is that?
You're calling on word[0]. This accesses the first element of the iterable string word. If word is empty (that is, word == ""), there is no "first element" to access; thus you get an IndexError. If a "word" starts with a non-alphabetic character (e.g. a number or a dash), then this will happen.
The second error you're having, with your second code snippet leaving off the last word, is because of the approach you're using for this problem. It looks like you're trying to walk through the sentence you're given, character by character, and decide whether to print a word after having read through it (which you know because you hit a space character. But this leads to the issue with your second approach, which is that it doesn't print the last string. That's because the last character in your sentence isn't a space - it's just the last letter in the last word. So, your else loop is never executed.
I'd recommend using an entirely different approach, using the method string.split(). This method is built-in to python and will transform one string into a list of smaller strings, split across the character/substring you specify. So if I do
quote = "Hello this is a sentence"
words = quote.split(' ')
print(words)
you'll end up seeing this:
['Hello', 'this', 'is', 'a', 'sentence']
A couple of things to keep in mind on your next approach to this problem:
You need to account for empty words (like if I have two spaces in a row for some reason), and make sure they don't break the script.
You need to account for non-alphanumeric characters like numbers and dashes. You can either ignore them or handle them differently, but you have to have something in place.
You need to make sure that you handle the last word at some point, even if the sentence doesn't end in a space character.
Good luck!
Instead of what you're doing, you can Iterate over each word in the string and count how many of them begin in those letters. Read about the function str.split(), in the parameter you enter the divider, in this case ' ' since you want to count the words, and that returns a list of strings. Iterate over that in the loop and it should work.
Okay so I am writing a program for python involving myself to make pig latin. Here is my code so far:
pig = input("What do you want to translate in pig latin? ")
pig = pig.lower()
for word in pig.split(' '):
last_char = word[-1]
word = word[:-1]
print(word + "ay")
How would I be able to grab the last character of any string regardless of it's length and place that character in front of the newly formed pig latin word?
Getting the last character of string is as simple as word[-1]. To add last character to the string you have to use string concatenation.
Have a look at inserting characters at the start and end of a string
Do you want to 'translate' several words or only one? If only one, you don't need a for loop. If several, you have to make sure you include print function in loop (otherwise, it will print only the last word). Also you can shorten your code by not using last_char variable (it wouldn't change readability much).
One word:
pig = input("What do you want to translate in pig latin? ")
pig = pig.lower()
word = pig[-1] + pig[:-1]
print(word + "ay")
Several words:
pig = input("What do you want to translate in pig latin? ")
pig = pig.lower()
for word in pig.split(' '):
word = word[-1] + word[:-1]
print(word + "ay")
I'm trying to use one function to count the number of words in a text file, after having this text file "cleaned" up by only including letters and single spaces. So i have my first function, which i want to clean up the text file, then i have my next function to actually return the length of the result of the previous function
(cleaned text). Here are those two functions.
def cleanUpWords(file):
words = (file.replace("-", " ").replace(" ", " ").replace("\n", " "))
onlyAlpha = ""
for i in words:
if i.isalpha() or i == " ":
onlyAlpha += i
return onlyAlpha
So words is the text file cleaned up without double spaces, hyphens, line feeds.
Then, i take out all numbers, then return the cleaned up onlyAlpha text file.
Now if i put return len(onlyAlpha.split()) instead of just return onlyAlpha...it gives me the correct amount of words in the file (I know because i have the answer). But if i do it this way, and try to split it into two functions, it screws up the amount of words. Here's what i'm talking about (here's my word counting function)
def numWords(newWords):
'''Function finds the amount of words in the text file by returning
the length of the cleaned up version of words from cleanUpWords().'''
return len(newWords.split())
newWords i define in main(), where `newWords = cleanUpWords(harper)-----harper is a varible that runs another read funtion (besides the point).
def main():
harper = readFile("Harper's Speech.txt") #readFile function reads
newWords = cleanUpWords(harper)
print(numWords(harper), "Words.")
Given all of this, please tell me why it gives a different answer if i split it into two functions.
for reference, here is the one that counts the words right, but doesn't split the word cleaning and word counting functions, numWords cleans and counts now, which isn't preffered.
def numWords(file):
'''Function finds the amount of words in the text file by returning
the length of the cleaned up version of words from cleanUpWords().'''
words = (file.replace("-", " ").replace(" ", " ").replace("\n", " "))
onlyAlpha = ""
for i in words:
if i.isalpha() or i == " ":
onlyAlpha += i
return len(onlyAlpha.split())
def main():
harper = readFile("Harper's Speech.txt")
print(numWords(harper), "Words.")
Hope i gave enough info.
The problem is quite simple: You split it into two function, but you completely ignore the result of the first function and instead calculate the number of words before the cleanup!
Change your main function to this, then it should work.
def main():
harper = readFile("Harper's Speech.txt")
newWords = cleanUpWords(harper)
print(numWords(newWords), "Words.") # use newWords here!
Also, your cleanUpWords function could be improved a bit. It can still leave double or triple spaces in the text, and you could also make it a bit shorter. Either, you could use regular expressions:
import re
def cleanUpWords(string):
only_alpha = re.sub("[^a-zA-Z]", " ", string)
single_spaces = re.sub("\s+", " ", only_alpha)
return single_spaces
Or you could first filter out all the illegal characters, and then split the words and join them back together with a single space.
def cleanUpWords(string):
only_alpha = ''.join(c for c in string if c.isalpha() or c == ' ')
single_spaces = ' '.join(only_alpha.split())
return single_spaces
Example, for which your original function would leave some double spaces:
>>> s = "text with triple spaces and other \n sorts \t of strange ,.-#+ stuff and 123 numbers"
>>> cleanUpWords(s)
text with triple spaces and other sorts of strange stuff and numbers
(Of course, if you intend to split the words anyway, double spaces are not a problem.)
I'm trying to convert a sentence to pig latin but I can;t get it to work.
Conditions:
1. If it starts with a vowel, add way to the word (e.g eagle become eagleway)
2. If it starts with a consonant, check the second character and so on for as long as it's a consonant, keep checking and strip it out and put it at the end. (e.g grain becomes aingr)
Here is my code so far:
x = "The apple is extremely tasty. Great!"
y = x.split()
for i in y:
if(i[0] == "a" or i[0]=="e" or i[0]=="i" or i[0]=="o" or i[0]=="u"):
print(i+"way", end = " ")
I managed to do part 1. but I can't figure out part 2. I don't understand how to go through the chars and strip the whole part.
Any help is appreciated.
Thanks.
Firstly, pick better variable names:
sentence = "The apple is extremely tasty. Great!"
words = sentence.split()
for word in words:
Secondly, you can simplify your first check:
if word[0] in "aeiou":
print("{0}way".format(word), end=" ")
Finally, you could use while and slicing to move characters from the start of the word to the end:
else:
while word[0] not in "aeiou":
word = "".join((word[1:], word[0]))
print(word, end=" ")
Note that this still doesn't quite do what you want:
eTh appleway isway extremelyway asty.t eat!Gr
I will leave dealing with letter cases and punctuation as an exercise; I suggest making everything one case or the other and removing all punctuation before iterating through words.