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?
using this code under, I want when the user input only letter q an error message...
using this code under, I want when the user input only letter q an error message appears that there is no second smallest, how I can do that? #include <iostream> #include <sstream> #include <vector> #include <algorithm> using namespace std; int secondSmallestNumber(vector<int> &I); int main() {    cout << "Enter the numbers in random order: (close by entering q)" << endl;    vector<int> I;    int input;    stringstream ss;    string str;    bool flag = false;    while (!flag) {        getline(cin, str);        ss.clear();        ss << str;...
When using scapy in python how can I get the same result as the snippit bellow?...
When using scapy in python how can I get the same result as the snippit bellow? (which in run in terminal) >>> sr(IP(dst="192.168.8.1")/TCP(dport=[21,22,23])) Received 6 packets, got 3 answers, remaining 0 packets (<Results: UDP:0 TCP:3 ICMP:0 Other:0>, <Unanswered: UDP:0 TCP:0 ICMP:0 Other:0>) >>> ans,unans=_ >>> ans.summary() IP / TCP 192.168.8.14:20 > 192.168.8.1:21 S ==> Ether / IP / TCP 192.168.8.1:21 > 192.168.8.14:20 RA / Padding IP / TCP 192.168.8.14:20 > 192.168.8.1:22 S ==> Ether / IP / TCP 192.168.8.1:22 >...
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 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...
(Python) This is my code for printing a roster for a team. When I print to...
(Python) This is my code for printing a roster for a team. When I print to the console, it makes the first player's name show up as number 2, and it says [] (its just blank for 1). How can I fix that so the first player's name is 1, not skipping 1 and going to 2. def file_to_dictionary(rosterFile): myDictionary={} myDict=[]    with open(rosterFile,'r') as f: for line in f:    (num,first,last,position)=line.split() myDictionary[num]= myDict myDict=[first, last, position] print (myDictionary) return...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT