Question

I am working on exercise 5.30 from Introduction to Computing using python (Author: Perkovic). I was...

I am working on exercise 5.30 from Introduction to Computing using python (Author: Perkovic).

I was looking at the solution and was able to understand what to do. However, when I implement the temp function as indicated, I keep getting this error "ValueError: the first two maketrans arguments must have equal length". However, it seems my two arguments are equal length, so I'm not sure what I am doing wrong!

print('Exercise 5.30')
def many(file):
infile = open(file)
content = infile.read()
infile.close

temp = str.maketrans('.,;!?:\n',7*'')

words = content.translate(temp).split()

count = [0,0,0,0]

for i in words:
if len(i)<= 4:
count[len(i)-1]+=1
for i in range(4):
print ('Words of length', len(words[i]),':',count[i])

print(many('sample.txt'))

Additionally, if I change the code to remove the translating function, why does it still include words with a char count > 4? I thought this statement removes it: if len(i)<= 4:

print('Exercise 5.30')
def many(file):
infile = open(file)
content = infile.read()
infile.close

words = content.split()

count = [0,0,0,0]

for i in words:
if len(i)<= 4:
count[len(i)-1]+=1
for i in range(4):
print ('Words of length', len(words[i]),':',count[i])

print(many('sample.txt'))

Lastly, the sample text includes: "This is a sample text file. This file containsa sample text but no sample or text. Text is in this file."

Thanks,

Karen

Homework Answers

Answer #1
def many(file):
    infile = open(file)
    content = infile.read()
    infile.close
    #code modifies  second arg should be 7*' '
    temp = str.maketrans('.,;!?:\n',7*' ')
    words = content.translate(temp).split()
    
    count = [0,0,0,0]

    for i in words:
        if len(i)<= 4:
            count[len(i)-1]+=1
    for i in range(4):
        print ('Words of length', len(words[i]),':',count[i])

In temp = str.maketrans('.,;!?:\n',7*' ') seocnd argument length should be same .

intitiall len(' 7*' ' ') would result in zero becuase len('') is zero .

after making it as 7*' ' which would give length as 7

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
WRITE USING PYTHON PROGRAMMING THE CODE GIVEN BELOW HAS SOME ERRORS WHICH NEED TO BE SOLVED....
WRITE USING PYTHON PROGRAMMING THE CODE GIVEN BELOW HAS SOME ERRORS WHICH NEED TO BE SOLVED. ALSO THE 2 POINTS MENTIONED BELOW SHOULD BE PRESENT IN THE CODE Write a script that calculates the 3 longest words of a text stored in a file and print them from the longest to the smaller of the 3. Please note: 1. The name of the file is word_list.csv and it doesn’t need to be asked to the user (meaning the name will...
I am a student taking python programming. Can this problem be modified using the define main...
I am a student taking python programming. Can this problem be modified using the define main method, def main()? import random #function definition #check for even and return 0 if even def isEven(number): if(number%2==0): return 0 #return 1 if odd else: return 1 #count variables even =0 odd = 0 c = 0 #loop iterates for 100 times for i in range(100): #generate random number n = random.randint(0,1000) #function call val = isEven(n) #check value in val and increment if(val==0):...
can someone edit my c++ code where it will output to a file. I am currently...
can someone edit my c++ code where it will output to a file. I am currently using xcode. #include <iostream> #include <cctype> #include <cstring> #include <fstream> using namespace std; bool inputNum(int [],int&,istream&); void multiply(int[],int,int[],int,int[],int&); void print(int[],int,int,int); int main() {ifstream input; int num1[35],num2[35],len1,len2,num3[60],len3=10,i; input.open("multiplyV2.txt"); //open file if(input.fail()) //is it ok? { cout<<"file did not open please check it\n"; system("pause"); return 1; }    while(inputNum(num1,len1,input)) {inputNum(num2,len2,input); multiply(num1,len1,num2,len2,num3,len3); print(num1,len1,len3,1); print(num2,len2,len3,2); for(i=0;i<len3;i++) cout<<"-"; cout<<endl; print(num3,len3,len3,1); //cout<<len1<<" "<<len2<<" "<<len3<<endl; cout<<endl;    } system("pause"); } void...
Python 3 Rewrite KNN sample code using KNeighborsClassifier . ● Repeat KNN Step 1 – 5,...
Python 3 Rewrite KNN sample code using KNeighborsClassifier . ● Repeat KNN Step 1 – 5, for at least five times and calculate average accuracy to be your result. ● If you use the latest version of scikit -learn, you need to program with Python >= 3.5. ● Use the same dataset: “ iris.data ” ● Split your data: 67% for training and 33% for testing ● Draw a line chart: Use a “for loop” to change k from 1...
So, i have this code in python that i'm running. The input file is named input2.txt...
So, i have this code in python that i'm running. The input file is named input2.txt and looks like 1.8 4.5 1.1 2.1 9.8 7.6 11.32 3.2 0.5 6.5 The output2.txt is what i'm trying to achieve but when the code runs is comes up blank The output doc is created and the code doesn't error out. it should look like this Sample Program Output 70 - 510, [semester] [year] NAME: [put your name here] PROGRAMMING ASSIGN MENT #2 Enter...
C Programming I am trying to also print the frequency and the occurrence of an input...
C Programming I am trying to also print the frequency and the occurrence of an input text file. I got the occurrence to but cant get the frequency. Formula for frequency is "Occurrence / total input count", this is the percentage of occurrence. Can someone please help me to get the frequency to work. Code: int freq[26] = {0}; fgets(input1, 10000, (FILE*)MyFile); for(i=0; i< strlen(input); i++) { freq[input[i]-'a']++; count++; } printf("Text count = %d", count); printf("\n"); printf("Frequency of plain text\n");...
In python: I am trying to construct a list using enumerate and takewhile from a Fibonaci...
In python: I am trying to construct a list using enumerate and takewhile from a Fibonaci generator. So far the code I have is the following: def fibonacci(): (a, b) = (0, 1) while True: yield a (a, b) = (b, a + b) def createlist(n, fib): return [elem for (i, elem) in enumerate(takewhile(lambda x: x < n, fib)) if i < n] I only get half the list when I do: print(createlist(n, fibonacci())) Output: [0, 1, 1, 2, 3,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):         self.name = name         self.pop = pop         self.area = area         self.continent = continent     def getName(self):         return self.name     def getPopulation(self):         return self.pop     def getArea(self):         return self.area     def getContinent(self):         return self.continent     def setPopulation(self, pop):         self.pop = pop     def setArea(self, area):         self.area = area     def setContinent(self, continent):         self.continent = continent     def __repr__(self):         return (f'{self.name} (pop:{self.pop}, size: {self.area}) in {self.continent} ') TASK 2 Python Program: File: catalogue.py from Country...
Assignment Statement Use the skeleton file starter code (below) to create the following classes using inheritance:...
Assignment Statement Use the skeleton file starter code (below) to create the following classes using inheritance: ⦁   A base class called Pet ⦁   A mix-in class called Jumper ⦁   A Dog class and a Cat class that each inherit from Pet and jumper ⦁   Two classes that inherit from Dog: BigDog and SmallDog ⦁   One classes that inherit from Cat: HouseCat The general skeleton of the Pet, Dog, and BigDog classes will be given to you (see below, "Skeleton", but...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT