I am trying to write a program that inputs a sentence from the keyboard, word by word, into a list. The program should output the following.
The complete sentence, with the first word capitalized if it wasnt already, spaces between each word, and a period at the end.
The count of the number of words in the sentence.
For instance, if the input is:
the
cat
ran
home
quickly
Your program should output:
The cat ran home quickly.
There are 5 words in the sentence.
listMessage = []
message = input('Enter first word of your message: ')
while message != 'done!':
listMessage.append(message)
message = input('Please enter the next word of your message or type done! when complete ')
return listMessage
Given that you already have listMessage, you can simply:
' '.join(listMessage).capitalize() + '.'
def function():
listMessage = []
message = input('Enter first word of your message: ').strip()
while message != 'done!':
listMessage.append(message)
message = input('Please enter the next word of your message or type done! when complete ')
text = ' '.join(listMessage).capitalize()+'.'
return text
You've got a couple things you might want to check here, according to your problem description.
If you want spaces between each word, you'll likely want to check to make sure that the words themselves, when entered, don't have leading or trailing spaces already. Use .strip() on your input to ensure this is the case.
If you want to capitalize the first letter of your sentence, you can check to see if listMessage[0][0].isupper() == True. This checks the first letter of the first word for capitalization.
If you'd like to add spaces to each string when you concatenate it, you can try a ranged for loop:
finalStr = ""
for str in listMessage:
finalStr += (str + " ")
(This will leave a space at the end, remember to .strip() it.)
Put it all together, and you've got your code. Try a working solution here!
You can try this:
word = ""
sentence = ""
while True:
word = input("Enter a word: ")
if word == 'done!':
break
sentence = sentence + word + " "
print(sentence)
Related
I have to solve the following problem:
-Write a program that takes a text as an entry and prints the same text without the letter 'r' in it.The teacher said that we have to use a list to put all the words in it and then remove the letter "r" from them. Here is how I started:
text = input("Enter some text: ")
l=text.split(" ")
for i in range(len(l)): #I want to use for to run the elements of the list
I don't know what to do next and what method I should use, I thought maybe the method remove() can be useful,but I don't know how to use it in each item of the list.
Welcome to SO, 👋
Here is my version.
statement = input("Enter some text: ")
listOfWords = statement.split(" ")
for i, word in enumerate(listOfWords):
if("r" in word.lower()):
print("found an instance of letter r in the word ({0})".format(word))
listOfWords[i]=word.replace("r", "")
sentence = " ".join(listOfWords)
print(sentence)
First - it grabs all the words from the input text as a list.
Then it iterates over all the words and if there is a "r" , it removes it from the word and updates the list as well. At the every end it generates the sentense back from the list.
Please note - this is ultra verbose code. It does not use Python features like List Comprehension, but it is much easier to understand. I purposefully added debug statements.
Please let me know if this works for you.
Thanks
For the list: str.split() will give a list of each item surrounded with whitespace (You can specify any delimiter you like)
Let's start with an individual list item... We will go with "Rollercoaster".
We can use the in keyword to check if a substring included in a larger string.
text = input("Enter some text: ")
result = ""
for ch in text.lower():
if ch == 'r':
continue
else:
result += ch
print(result)
Returns
Enter some text: rollercoster
ollecoste
Process finished with exit code 0
i need to make a program that will capitalize the first word in a sentence and i want to be sure that all the special characters that are used to end a sentence can be used.
i can not import anything! this is for a class and i just want some examples to do this.
i have tried to use if to look in the list to see if it finds the matching character and do the correct split operatrion...
this is the function i have now... i know its not good at all as it just returns the original string...
def getSplit(userString):
userStringList = []
if "? " in userString:
userStringList=userString.split("? ")
elif "! " in userStringList:
userStringList = userString.split("! ")
elif ". " in userStringList:
userStringList = userString.split(". ")
else:
userStringList = userString
return userStringList
i want to be able to input something like this is a test. this is a test? this is definitely a test!
and get [this is a test.', 'this is a test?', 'this is definitely a test!']
and the this is going to send the list of sentences to another function to make the the first letter capitalized for each sentence.
this is an old homework assignment that i could only make it use one special character to separate the string into a list. buti want to user to be able to put in more then just one kind of sentence...
This may hep. use str.replace to replace special chars with space and the use str.split
Ex:
def getSplit(userString):
return userString.replace("!", " ").replace("?", " ").replace(".", " ").split()
print(map(lambda x:x.capitalize, getSplit("sdfsdf! sdfsdfdf? sdfsfdsf.sdfsdfsd!fdfgdfg?dsfdsfgf")))
Normally, you could use re.split(), but since you cannot import anything, the best option would be just to do a for loop. Here it is:
def getSplit(user_input):
n = len(user_input)
sentences =[]
previdx = 0
for i in range(n - 1):
if(user_input[i:i+2] in ['. ', '! ', '? ']):
sentences.append(user_input[previdx:i+2].capitalize())
previdx = i + 2
sentences.append(user_input[previdx:n].capitalize())
return "".join(sentences)
I would split the string at each white space. Then scan the list for words that contain the special character. If any is present, the next word is capitalised. Join the list back at the end. Of course, this assumes that there are no more than two consecutive spaces between words.
def capitalise(text):
words = text.split()
new_words = [words[0].capitalize()]
i = 1
while i < len(words) - 1:
new_words.append(words[i])
if "." in words[i] or "!" in words[i] or "?" in words[i]:
i += 1
new_words.append(words[i].capitalize())
i += 1
return " ".join(new_words)
If you can use the re module which is available by default in python, this is how you could do it:
import re
a = 'test this. and that, and maybe something else?even without space. or with multiple.\nor line breaks.'
print(re.sub(r'[.!?]\s*\w', lambda x: x.group(0).upper(), a))
Would lead to:
test this. And that, and maybe something else?Even without space. Or with multiple.\nOr line breaks.
I am completely new to python so please excuse me. I try to learn python on a website called Codecademy. It all works fine, however I wanted to see what would happen if I insert a script from the website into python on my PC. I have currently installed the second version of python (2.7.13).
The script is the following:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word [0]
new_word = word + first + pyg
# All the different variables are now in one
new_word = new_word[1:len(new_word)]
# The first two letters are removed
print new_word
else:
print 'empty'
# If there is no input or any input containing non-letter characters
When I open this script via python, I am able to enter the first question, but as soon as I hit enter, the program closes and I can not get to my second question. I tried loading it via cmd directly, but it didn´t work either.
Just add this line after your output:
raw_input('Enter any key to exit: ")
This will keep it open until you hit a key and click enter.
There is no "second question" -- you have only one input statement in your control flow. If you want the program to repeat, you need to code that. A simple version:
while True:
# Get user input
original = raw_input('Enter a word:')
# Convert to Pig Latin
... continue with your original code
# Print result
Granted, this will loop forever. You can set a check in the loop for a "quit" input, if you like. I leave that as a further exercise for the student.
The complete solution of your query:
Note(You said the first two letter is removed but in your code you wrote [1:]-- that means it removed only first letter)
pyg = 'ay'
want_continue = True
while want_continue:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word [0]
new_word = word + first + pyg
# All the different variables are now in one
new_word = new_word[2:len(new_word)]
# The first two letters are removed
print new_word
else:
print 'empty'
# If there is no input or any input containing non-letter characters
user_input = raw_input('Want to Contiue:(Y)')
if user_input.lower() != 'y':
want_continue = False
My code takes sentence and finds a given a word in that sentence.
If the word is in the sentence it needs to say that it has found the word and what positions said word is in.
If the word is not in the sentence it should display an error message.
I have this:
print("Please insert your sentence without punctuation")
sentence=(input())
variable1='sentence'
print("Which word would you like to find in your sentence?")
word=input()
variable2='word'
if 'word'=='COUNTRY':
'variable3'==5
'variable4'==17
if word in sentence:
print([word], "is in positions", [variable3], "and", [variable4]);
else:
print("Your word is not in the sentence!")
I want to deal with some misunderstandings in the presented code.
First,
print("Please insert your sentence without punctuation")
sentence=(input())
is simpler as
sentence = input("Please insert your sentence without punctuation")
Now I have a variable called sentence wihich should not be muddled with the string 'sentence'
Similarly we can say
word = input("Which word would you like to find in your sentence?")
gives another variable word again not to be muddled with the string 'word'
Suppose for the sake of argument we have,
sentence = "Has this got an elephant in?"
and we search for the word 'elephant'
The posted code attempts to use in, but this will happen:
>>> "elephant" in sentence
True
>>> "ele" in sentence
True
>>> "giraffe" in sentence
False
>>>
Close. But not close enough. It is not looking for a whole word, since we found 'ele' in 'elephant'.
If you split the sentence into words, as suggested by the other answer, you can then search for whole words and find the position. (Look up split; you can choose other characters than the default ' ').
words = sentence.split()
word = 'ele'
words.index(word)
If the word isn't there you will get an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'ele' is not in list
I will leave the error handling to you.
Python sequences provide the index method. It gives you the index of an element, or raises an error if the element is not in the sequence. On strings, it allows you to find substrings.
>>> 'hello world'.index('world')
6
>>> 'hello world'.index('word')
ValueError: substring not found
Basically, you have to add input for the sentence and the word to search. That's it.
print("Insert sentence without punctuation...")
sentence=input() # get input, store it to name `sentence`
print("Insert word to find...")
word=input()
try:
idx = sentence.index(word)
except ValueError: # so it wasn't in the sentence after all...
print('Word', word, 'not in sentence', repr(sentence))
else: # if we get here, IndexError was NOT thrown
print('Word', word, 'first occurs at position', idx)
There are some caveats here, for example 'fooworldbar' will match as well. The correct handling of such things depend on what precisely one wants. I'm guessing you actually want word positions.
If you need positions in the meaning of "the nth word", you must transform the sentence to a list of words. str.split does that. You can then work with index again. Also, if you want all positions, you must call index repeatedly.
print("Insert sentence without punctuation...")
sentence = input() # get input, store it to name `sentence`
words = sentence.split() # split at whitespace, creating a list of words
print("Insert word to find...")
word=input()
positions, idx = [], -1
while idx < len(words):
try:
idx = words.index(word, idx+1)
except ValueError: # so it wasn't in the rest of the sentence after all...
break
else: # if we get here, IndexError was NOT thrown
positions.append(idx) # store the index to list of positions
# if we are here, we have searched through the whole string
if positions: # positions is not an empty list, so we have found some
print('Word', word, 'appears at positions', ', '.join(str(pos) for pos in positions))
else:
print('Word', word, 'is not in the sentence')
You can use re module:
import re
sentence = input('Sentence: ')
word = input('Word: ')
## convert word in regular expression for search method.
regex_word = r'(' + word + ')(?=\s|$)'
## initialize search var.
search = re.search(regex_word, sentence)
if search:
while search:
match_pos = search.span()
sentence = sentence[:match_pos[0]] + sentence[match_pos[1]:]
print(word + ' is in position ' + str(match_pos[0]))
search = re.search(regex_word, sentence)
else:
print(word + ' is not present in this sentence')
print("sentence analyser")
sentence = input("type in the sentence that you want the program to analyse: ")
keyword = input("type in the word that you want the program to find the position of: ")
sentence = sentence.strip("!£$%^&*()-""_=+[{]}'##~/?")
sentence = sentence.title()
keyword = keyword.title()
sentence = sentence.split()
while keyword not in sentence:
keyword = input('word: ')
for (position,words) in enumerate(sentence):
if (keyword in words):
print("the position of your word is",position+1)
whenever i type the a word which is in the sentence it works fine, but when i type a word which is not in the sentence it asks me to input another word(as it should) but when i input a word which is in the sentence it just keeps asking me to input a correct word instead of telling me its position in the sentence> thank you hope you can help
Since you do sentence = sentence.title() all the words are in Title Case. Then when for the first time you ask for a word you do keyword = keyword.title(), so the word is also in Title Case.
But if it doesn't match you only ask for a new word, but don't title() it so it won't match unless you write it in Title Case yourself.
Fix:
while keyword not in sentence:
keyword = input('word: ').title()