Question

In: Computer Science

I have the following python code. I get the following message when running it using a...

I have the following python code. I get the following message when running it using a test script which I cannot send here:

while textstring[iterator].isspace(): # loop until we get other than space character

IndexError: string index out of range. Please find out why and correct the code.

def createWords(textstrings):
        createdWords = [] # empty list
        for textstring in textstrings: # iterate through each string in trxtstrings
                iterator = 0
                begin = iterator # new begin variable
                while (iterator < len(textstring)): # iterate through each character in the string
                        finished = iterator # new finished character
                        while textstring[iterator].isspace(): # loop until we get other than space character
                                iterator = iterator+1
                                word = textstring[begin:finished+1].strip() #  extract the word from begin position to before the space character,
                                                                                                                        #  textstring[begin,finshed] ; strip() will remove white spaces at ends
                                if (word): # if word is not empty
                                        createdWords.append(word) # append new word to createWords
                                begin = iterator # update begin value with current iterator position
                        if (textstring[iterator]).isalpha():
                                if (textstring[iterator].isupper()): # if letter is in uppercase  change it to lower case by using letter.lower() method.
                                        textstring = textstring[:iterator] + textstring[iterator].lower() + textstring[iterator+1:]
                                print(textstring[iterator],"this a letter")
                        elif (textstring[iterator]).isdigit():
                                print(textstring[iterator],"is a digit")
                        else:
                                print(textstring[iterator],"this a symbol")
                                word = textstring[begin:finished].strip()       #  extract the word from begin position to before the symbol character,
                                                                                                                        #  textstring[begin,finshed] ; strip() will remove white spaces at ends
                                createdWords.append(word) # append new word to createWords
                                begin = iterator  # update begin value with current iterator position
                        iterator= iterator+1 # increment iterator value
                word = textstring[begin:iterator].strip()  #  extract the word from begin position to the end of the string
                createdWords.append(word) # append new word to createWords
        return createdWords # return createWords

Solutions

Expert Solution

I found below 2 solutions for this. Pick whichever solution works for you.

SOLUTION 1:

While calling the function createWords(textstrings), send a list of sentences like shown below

OUTPUT:

SOLUTION 2:

Remove the first for loop and change the variable name in createwords from "textstrings" to "textstring".

Below is the updated code

OUTPUT:

Code to copy:

def createWords(textstring):
        createdWords = [] # empty list
        #for textstring in textstrings: # iterate through each string in trxtstrings
        iterator = 0
        begin = iterator # new begin variable
        while (iterator < len(textstring)): # iterate through each character in the string
                finished = iterator # new finished character
                while textstring[iterator].isspace(): # loop until we get other than space character
                        iterator = iterator+1
                        word = textstring[begin:finished+1].strip() #  extract the word from begin position to before the space character,
                         #  textstring[begin,finshed] ; strip() will remove white spaces at ends
                        if (word): # if word is not empty
                                createdWords.append(word) # append new word to createWords
                        begin = iterator # update begin value with current iterator position
                if (textstring[iterator]).isalpha():
                        if (textstring[iterator].isupper()): # if letter is in uppercase  change it to lower case by using letter.lower() method.
                                textstring = textstring[:iterator] + textstring[iterator].lower() + textstring[iterator+1:]
                        print(textstring[iterator],"this a letter")
                elif (textstring[iterator]).isdigit():
                        print(textstring[iterator],"is a digit")
                else:
                        print(textstring[iterator],"this a symbol")
                        word = textstring[begin:finished].strip()       #  extract the word from begin position to before the symbol character,
                        #  textstring[begin,finshed] ; strip() will remove white spaces at ends
                        createdWords.append(word) # append new word to createWords
                        begin = iterator  # update begin value with current iterator position
                iterator= iterator+1 # increment iterator value
        word = textstring[begin:iterator].strip()  #  extract the word from begin position to the end of the string
        createdWords.append(word) # append new word to createWords
        return createdWords # return createWords

ret = createWords("HELLO, How are you")
print(ret)

Related Solutions

What does it mean when you get an error message running SPSS forbinary linear regression...
What does it mean when you get an error message running SPSS for binary linear regression that states the dependent variable has more than two non-missing values. For logistic regression, the dependent variable value must assume exactly two values on the cases being processed. What do I need to do to fix this issue?
Java homework problem: I need the code to be able to have a message if I...
Java homework problem: I need the code to be able to have a message if I type in a letter instead of a number. For example, " Please input only numbers". Then, I should be able to go back and type a number. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class LoginGui {    static JFrame frame = new JFrame("JFrame Example");    public static void main(String s[]) {        JPanel panel...
Using python, produce code that mimics some ATM transactions: a. A welcome message must be displayed...
Using python, produce code that mimics some ATM transactions: a. A welcome message must be displayed initially reflecting the appropriate time of day (for example: Good Night, Welcome to Sussex Bank). b. Assume the user’s account balance is $5375.27. c. Allow the user to enter a pin number that does not have to be validated: def atm_login(): pin_number = input("Please enter your (4 digit) pin number: ") # display welcome message welcome_message() d. The message should be followed by a...
I cannot get this code to run on my python compiler. It gives me an expected...
I cannot get this code to run on my python compiler. It gives me an expected an indent block message. I do not know what is going on. #ask why this is now happenning. (Create employee description) class employee: def__init__(self, name, employee_id, department, title): self.name = name self.employee_id = employee_id self.department = department self.title = title def __str__(self): return '{} , id={}, is in {} and is a {}.'.format(self.name, self.employee_id, self.department, self.title)    def main(): # Create employee list emp1...
I need to add this checkpoint to an existing code that i have in python Checkpoint...
I need to add this checkpoint to an existing code that i have in python Checkpoint 1: Once you have created and tested the Bank Account Class create subclasses to the BankAccount class. There should be two subclasses, CheckingAccount and SavingsAccount. You should add interest_rate to the parent BankAccount class. To the CheckingAccount add variables called per_check_fee default to false and allow_overdraft default to True. To SavingsAccount add the variable transactions_per_month, default it to 5. Create instances of CheckingAccount and...
Complete the following in syntactically correct Python code. 1. The program should display a message indicating...
Complete the following in syntactically correct Python code. 1. The program should display a message indicating whether the person is an infant, a child, a teenager, or an adult. Following are the guidelines: a. If the person is older than 1 year old or less, he or she is an infant. b. If the person is older than 1 year, but younger than 13, he or she is a child c. If the person is at least 13 years old,...
I get the following errors when I type the code #include <iostream> #include <string.h> #include <bitset>...
I get the following errors when I type the code #include <iostream> #include <string.h> #include <bitset> #include <math.h> #define IS_INTEGRAL(T) typename std::enable_if< std::is_integral<T>::value >::type* = 0 using namespace std; template<class T> std::string inttobits1(T byte, IS_INTEGRAL(T)) { std::bitset<sizeof(T)* CHAR_BIT> bs(byte); return bs.to_string(); } int bitstoint1(string bits) { int value; for (int x = 0, y = bits.length() - 1;x < 8 && x < bits.length();x++) { int val = atoi(bits.substr(y, 1).c_str()); value += (int)val * pow(2, x); } return value; }...
I have to code the assignment below. I cannot get the program to work and I...
I have to code the assignment below. I cannot get the program to work and I am not sure what i am missing to get the code to work past the input of the two numbers from the user. My code is listed under the assignment details. Please help! Write a Java program that displays the prime numbers between A and B. Inputs: Prompt the user for the values A and B, which should be integers with B greater than...
Code in python the grocery receipt the following steps using the knowledge you have. declare a...
Code in python the grocery receipt the following steps using the knowledge you have. declare a string variable called card_number. Assign a value of “xxx8974” declare a string variable called date and assign a string value of “9\7\2020” You need to use an escape sequence for the slashes in this string. See Mosh’s video 2.4-Escape Sequence if needed. You do not need to use a date class variable as we have not learned that data type yet. Use a simple...
Using python code Developed a program to get students homework, midterm, and final exam grades and...
Using python code Developed a program to get students homework, midterm, and final exam grades and compute their average grades display average grade as a number and give them letter gardes. For this homework, I would like you to modify your to do the following. Student grades MUST be between 0 and 100. If students input any number that is not in this range , program must keep asking to enter the correct number. Once student input correct grade, program...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT