Post: Python Task
09-21-2016, 12:54 PM #1
Ali
Can’t trickshot me!
(adsbygoogle = window.adsbygoogle || []).push({});
    
import re
while True:
*** sentence = input("Enter a sentence: ").casefold()
*** if not re.match("^[a-zA-Z ]*$", sentence):
******* print("Error! Only letters a-z allowed!")
*** else:
******* sentence.split()
*** break
splitsentence = sentence.split()
word = input("Enter a word from your sentence.")
if word in splitsentence:
* print("The word:",word, "is located on word number(s):", splitsentence.index(word)+ 1)
else:
* print("Error! Word not found in your sentence.")

I need to make it so if a word appears more than once in the sentence. It should output all the word positions that specific word is located. Currently it will only output the first word position it recognises.

Example:
Sentence: Ali is my name Ali Ali
Output: The word "Ali" is located on word number(s): 1

I need it to output: The word "Ali" is located on word number(s): 1, 5, 6
09-21-2016, 03:08 PM #2
Originally posted by Ali View Post
    
import re
while True:
*** sentence = input("Enter a sentence: ").casefold()
*** if not re.match("^[a-zA-Z ]*$", sentence):
******* print("Error! Only letters a-z allowed!")
*** else:
******* sentence.split()
*** break
splitsentence = sentence.split()
word = input("Enter a word from your sentence.")
if word in splitsentence:
* print("The word:",word, "is located on word number(s):", splitsentence.index(word)+ 1)
else:
* print("Error! Word not found in your sentence.")

I need to make it so if a word appears more than once in the sentence. It should output all the word positions that specific word is located. Currently it will only output the first word position it recognises.

Example:
Sentence: Ali is my name Ali Ali
Output: The word "Ali" is located on word number(s): 1

I need it to output: The word "Ali" is located on word number(s): 1, 5, 6


    
import re

def main():
sentence = input("Enter a sentence: ").casefold()
if not re.match("^[a-zA-Z ]*$", sentence):
print("Error! Only letters a-z allowed!")
return

word_count = len(sentence.split())
word = input("Enter a word from your sentence: ")
occurences = [occurence.start() for occurence in re.finditer(word, sentence)]
print("The word {} is located at: {}".format(word, str(occurences)))

if __name__ == "__main__":
main()


This will print out the indices of each word (the character they're located at, not the word)

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo