how do i make my while loop work? - python

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()

Related

Take word by word input and output a sentence

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)

Need my code to count each words position number and store to file

I need to develop a program on python that identifies individual words in a sentence and stores them in a list but stores a word's position number in the sentence not the actual word. I have developed this code yet cannot get it to save the words position.
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
for i, word in enumerate(words):
if keyword == word:
print(i+1)
file = open("newfile.txt","a")
file.write(input("text to write in the file")+"/n")
file.close()
Anyone got any advice, pointers or help?
Based on you question and the code snippet, I have come to a conclusion that your program,
Accept sentence from user
Get a keyword from user
If the word in sentence matches the keyword, save the word number in file.
So, for that, Here's the code.
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
file=open("newfile.txt","a") #open the file in append mode
for i, word in enumerate(words):
if keyword == word:
file.write(str(i+1)+" ") #append the text. I've added space to distiguish digit.
file.close() #Close the file after loop.

Need assistance with sentence analysis

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')

Find and select a required word from a sentence?

I am trying to get raw_input from user and then find a required word from that input. If the required word is there, then a function runs. So I tried .split to split the input but how do I find if the required word is in the list.
It's really simple to get this done. Python has an in operator that does exactly what you need. You can see if a word is present in a string and then do whatever else you'd like to do.
sentence = 'hello world'
required_word = 'hello'
if required_word in sentence:
# do whatever you'd like
You can see some basic examples of the in operator in action here.
Depending on the complexity of your input or lack of complexity of your required word, you may run into some problems. To deal with that you may want to be a little more specific with your required word.
Let's take this for example:
sentence = 'i am harrison'
required_word = 'is'
This example will evaluate to True if you were to doif required_word in sentence: because technically the letters is are a substring of the word "harrison".
To fix that you would just simply do this:
sentence = 'i am harrison'
required_word = ' is '
By putting the empty space before and after the word it will specifically look for occurrences of the required word as a separate word, and not as a part of a word.
HOWEVER, if you are okay with matching substrings as well as word occurrences then you can ignore what I previously explained.
If there's a group of words and if any of them is the required one, then what should I do? Like, the required word is either "yes" or "yeah". And the input by user contains "yes" or "yeah".
As per this question, an implementation would look like this:
sentence = 'yes i like to code in python'
required_words = ['yes', 'yeah']
^ ^ ^ ^
# add spaces before and after each word if you don't
# want to accidentally run into a chance where either word
# is a substring of one of the words in sentence
if any(word in sentence for word in required_words):
# do whatever you'd like
This makes use of the any operator. The if statement will evaluate to true as long as at least one of the words in required_words is found in sentence.
Harrison's way is one way. Here are other ways:
Way 1:
sentence = raw_input("enter input:")
words = sentence.split(' ')
desired_word = 'test'
if desired_word in words:
# do required operations
Way 2:
import re
sentence = raw_input("enter input:")
desired_word = 'test'
if re.search('\s' + desired_word + '\s', sentence.strip()):
# do required operations
Way 3 (especially if there are punctuations at the end of the word):
import re
sentence = raw_input("enter input:")
desired_word = 'test'
if re.search('\s' + desired_word + '[\s,:;]', sentence.strip()):
# do required operations

How can I adapt this code to use the enumerate() function to find the position of a word in a string? [duplicate]

This question already has answers here:
How to find all occurrences of a substring?
(32 answers)
Closed 6 years ago.
sentence = input("please enter a sentence")
keyword = input("enter a word you want to find in the string")
sentence = sentence.lower()
keyword = keyword.lower()
sentence = sentence.split(' ')
if keyword in sentence:
pos = sentence.index(keyword)
pos = pos+1
print(pos)
else:
print ("The keyword you entered is not in the sentence you entered")
It has to be able to find the word if it occurs more than once.
Based on your comments saying that you don't actually need to use enumerate(), but don't know of a way to not use it, your question is misleading. My previous answer, which I deleted, used enumerate() and printed out the index of the keyword in an array of the words, which was incorrect.
In order to output the index of the keyword in your sentence string, as opposed to an array of the words, you could do the following, which I adapted using the link which I posted in a comment:
import re
sentence = raw_input("Please enter a sentence:\n")
keyword = raw_input("Enter a word you want to find in the string: ")
sentence = sentence.lower()
keyword = keyword.lower()
if keyword in sentence:
positions = [m.start() for m in re.finditer(keyword, sentence)]
for pos in positions:
print(pos)
else:
print ("The keyword you entered is not in the sentence you entered")
This outputs the following:
Please enter a sentence:
blah test test yada 123 test
Enter a word you want to find in the string: test
5
10
24

Categories