So, here is what I got:
def getSentence():
sentence = input("What is your sentence? ").upper()
if sentence == "":
print("You haven't entered a sentence. Please re-enter a sentence.")
getSentence()
elif sentence.isdigit():
print("You have entered numbers. Please re-enter a sentence.")
getSentence()
else:
import string
for c in string.punctuation:
sentence = sentence.replace(c,"")
return sentence
def list(sentence):
words = []
for word in sentence.split():
if not word in words:
words.append(word)
print(words)
def replace(words,sentence):
position = []
for word in sentence:
if word == words[word]:
position.append(i+1)
print(position)
sentence = getSentence()
list = list(sentence)
replace = replace(words,sentence)
I have only managed to get this far, my full intention is to take the sentence, seperate into words, change each word into a number e.g.
words = ["Hello","world","world","said","hello"]
And make it so that each word has a number:
So lets say that "hello" has the value of 1, the sentence would be '1 world world said 1'
And if world was 2, it would be '1 2 2 said 1'
Finally, if "said" was 3, it would be '1 2 2 1 2'
Any help would be greatly appreciated, I will then develop this code so that the sentence and such is stored into a file using file.write() and file.read() etc
Thanks
If you want just the position in which each word is you can do
positions = map(words.index,words)
Also, NEVER use built-in function names for your variables or functions. And also never call your variables the same as your functions (replace = replace(...)), functions are objects
Edit: In python 3 you must convert the iterator that map returns to a list
positions = list(map(words.index, words))
Or use a comprehension list
positions = [words.index(w) for w in words]
Does it matter what order the words are turned into numbers? Is Hello and hello two words or one? Why not something like:
import string
sentence = input() # user input here
sentence.translate(str.maketrans('', '', string.punctuation))
# strip out punctuation
replacements = {ch: str(idx) for idx, ch in enumerate(set(sentence.split()))}
# builds {"hello": 0, "world": 1, "said": 2} or etc
result = ' '.join(replacements.get(word, word) for word in sentence.split())
# join back with the replacements
Another idea (although don't think it's better than the rest), use dictionaries:
dictionary = dict()
for word in words:
if word not in dictionary:
dictionary[word] = len(dictionary)+1
Also, on your code, when you're calling "getSentence" inside "getSentence", you should return its return value:
if sentence == "":
print("You haven't entered a sentence. Please re-enter a sentence.")
return getSentence()
elif sentence.isdigit():
print("You have entered numbers. Please re-enter a sentence.")
return getSentence()
else:
...
Related
This is the function:
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0]
return result.upper()
This is an exercise on my online course. The objective is to return the first initials of a string capitalized. For example, initials ("Universal Serial Bus") should return "USB".
phrase is a str type object.
str objects can have functions applied to them through their methods. split is a function that returns a list containing multiple str objects. This is stored in words
the for word in words takes each element of words and puts it in the variable word for each iteration of the loop.
The += function adds the first letter of word to result by accessing the first character of the str by using the [0] index of word.
Then the upper function is applied to the result.
I hope this clears it up for you.
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0]
return result.upper()
This:
Splits the phrase at every space (" "), with phrase.split(). .split() returns a list which is assigned to words
Iterates through the list words and adds the first letter of each word (word[0]) to the result variable.
Returns result converted to uppercase (result.upper())
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].upper()
return result
print(ShortName("Active Teens Taking Initiative To Understand Driving Experiences"))
Should be: ATTITUDE
def initials(phrase):
words =phrase.split()
result=""+""
for word in words:
result += word[0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
Here is output:
USB
LAN
OS
This:
Splits the phrase at every space (" "+" ") and concatenate next one first letter,with phrase.split() returns a list which is assigned to words Iterates through the list words and adds the first letter of each word (word[0]) to the result variable.
Returns result converted to uppercase (result.upper())
strong text
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].uppper()
return result
Problem 1.
This problem provides practice using a while True loop. Write a function named
twoWords that gets and returns two words from a user. The first word is of a
specified length, and the second word begins with a specified letter.
The function twoWords takes two parameters:
an integer, length, that is the length of the first word and
a character, firstLetter, that is the first letter of the second word.
The second word may begin with either an upper or lower case instance of
firstLetter. The function twoWords should return the two words in a list. Use
a while True loop and a break statement in the implementation of twoWords. The
following is an example of the execution of twoWords:
print(twoWords(4, 'B')):
A 4-letter word please two
A 4-letter word please one
A 4-letter word please four
A word beginning with B please apple
A word beginning with B please pear
A word beginning with B please banana
['four', 'banana']
This is what I have so far, but it keeps asking me the first question over again
even if I have the right word length. What am I doing wrong?
def twoWords(length, firstLetter):
wordLen = input('A 4-letter word please ')
while len(wordLen) != int(length):
wordlen = input('A 4-letter word please ')
word = input('A word beginning with ' + firstLetter + ' please ')
while word[0] != firstLetter:
word = input('A word beginning with ' + firstLetter + ' please ')
return[wordLen, word]
def twoWords(length,firstLetter):
firstWord = ""
secondWord= ""
while True:
firstWord = input('A ' + str(length) + '-letter word please.')
if length == len(firstWord):
break
while True:
secondWord = input('A word beginning with ' + firstLetter+ ' please')
if secondWord[0] == firstLetter.upper() or secondWord[0] == firstLetter.lower():
break
return [firstWord,secondWord]
print(twoWords(4,'B'))
def twoWord(length, firstLetter):
while True:
word1=(input("Enter a "+ str(length)+"-letter word please:"))
if len(word1)==int(length):
break
while True:
word2=input("Please enter the word beginning with "+firstLetter+" please:")
if word2[0].upper()==firstLetter or word2[0].lower()==firstLetter:
break
return word1, word2
print(twoWord(5, 'b'))
The code I have made:
asks the user for a sentence,
makes it lower case so it is not case sensitive
splits the sentence into separate words so each word can have a number assigned to it according to its position
How can I add a part to my code that saves the sentence inputted by
the user as a file, along with the numbers that get assigned to each
word?
Here is my code:
sentence = input("Please enter a sentence")
sentence = sentence.lower()
sentence = sentence.split()
positions = [sentence.index (x) +1 for x in sentence]
print(sentence)
print(positions)
Use raw_input if you want to treat everything as strings. You do not need to store the positions but, instead, get them from the wonderful enumerate function. Then write to the file like so
sentence = raw_input("Please enter a sentence: ")
sentence = sentence.lower()
sentence = sentence.split()
open('filename.txt','w').writelines(["%d-%s\n"%(i+1,x) for (i,x) in enumerate(sentence)])
sentence = input("Please enter a sentence")
sentence = sentence.lower()
sentence = sentence.split()
wordPositionDict = {}
( wordPositionDict.get(x,[]).append(i+1) for i,x in enumerate(sentence))
print wordPositionDict[word]
append all the index for each word to dict. after iterate all the words in sentence you will have one dict which key is the words and value is the list of index
I Am writing a function that should take a string input and return the string with every first letter of every word as a capital letter, I have achieved this to a certain degree.
My Code:
string = input("Please Enter A string:")
def capitalize_words(string):
split = string.split()
letter1 = ''
letter2 = ''
letter3 = ''
str1 = split[0]
str2 = split[1]
str3 = split[2]
for i in str1:
if i in str1[0]:
first = i.upper()
else:
letter1 = letter1 + i
string1 = (first+letter1)
for i in str2:
if i in str2[0]:
first = i.upper()
else:
letter2 = letter2 + i
string2 = (first+letter2)
for i in str3:
if i in str3[0]:
first = i.upper()
else:
letter3 = letter3 + i
string3 = (first+letter3)
result = string1+' '+string2+' '+string3
return result
func = capitalize_words(string)
print(func)
Input:
Please Enter A string:herp derp sherp
Output:
Herp Derp Sherp
However this is very inflexible because i can only enter 3 words with spaces no more no less , this makes for a rather primal program. I would like to be able to enter anything and get the desired result of the first letter of every word being a capital letter no matter how many words i enter.
I fear with my skills this is as far as I am able to get, can you please improve my program if possible.
>>> print(raw_input('Please Enter A string: ').title())
Please Enter A string: herp derp sherp
Herp Derp Sherp
Use str.title() to achieve what you want in one go.
But to process words in a sentence, use a loop instead of a series of local variables; here is a version that does the same what you are doing for an arbitrary number of words:
for i, word in enumerate(split):
split[i] = word[0].upper() + word[1:]
result = ' '.join(split)
I used string slicing as well to select just the first character, and all but the first character of a word. Note the use of enumerate() to give us a counter which wich we can replace words in the split list directly.
An alternative method is to use re.sub such as:
re.sub(r'\b.', lambda c: c.group().upper(), 'herp derp sherp and co.')
# 'Herp Derp Sherp And Co.'
You could write this in a one-line generator expression:
def upper_case(text):
return ' '.join(w[0].upper() + w[1:] for w in text.split())
Notice, that this function fails on single letter words and replaces any whitespace by a single space character.
Use this as
In [1]: upper_case(input('Please Enter A string: '))
Please Enter A string: hello world
Out[1]: 'Hello World'
I am trying to create a program in python that takes a sentence from a user and jumbles the middle letters of said word, but keeping the other letters intact...Right now I have code that will rearrange all the user input's and just forgets about the spaces...I'll let my code speak for myself.. IT works fine for a single word input, I guess I will just summarize it...
I need to randomize each word the user enters keeping the other words intact afterwards..
import random
words = input("Enter a word or sentence") #Gets user input
words.split()
for i in list(words.split()): #Runs the code for how many words there are
first_letter = words[0] #Takes the first letter out and defines it
last_letter = words[-1] #Takes the last letter out and defines it
letters = list(words[1:-1]) #Takes the rest and puts them into a list
random.shuffle(letters) #shuffles the list above
middle_letters = "".join(letters) #Joins the shuffled list
final_word_uncombined = (first_letter, middle_letters, last_letter) #Puts final word all back in place as a list
final_word = "".join(final_word_uncombined) #Puts the list back together again
print(final_word) #Prints out the final word all back together again
Your code is almost right. Corrected version would be like this:
import random
words = raw_input("Enter a word or sentence: ")
jumbled = []
for word in words.split(): #Runs the code for how many words there are
if len(word) > 2: # Only need to change long words
first_letter = word[0] #Takes the first letter out and defines it
last_letter = word[-1] #Takes the last letter out and defines it
letters = list(word[1:-1]) #Takes the rest and puts them into a list
random.shuffle(letters) #shuffles the list above
middle_letters = "".join(letters) #Joins the shuffled list
word = ''.join([first_letter, middle_letters, last_letter])
jumbled.append(word)
jumbled_string = ' '.join(jumbled)
print jumbled_string
So I read this question, during lunch at the apartment, then I had to wade through traffic. Anyways here is my one line contribution. Seriously alexeys' answer is where it's at.
sentence = input("Enter a word or sentence")
print " ".join([word[0] + ''.join(random.sample(list(word[1:-1]), len(list(word[1:-1])))) + word[-1] for word in sentence.split()])
If i understand your question correctly it looks like you are on track, you just have to extend this for every word
randomized_words = []
for word in words.split():
#perform your word jumbling
radomized_words.append(jumbled_word)
print ' '.join(randomized_words)
This creates a separate jumbled word list. Each word in the users word input is jumbled and added to the list to retain order. At the end, the jumbled words list is printed. Each word is in the same order as entered by the user but the letters are jumbled.