0

counts the occurrences of letter a in the first 200 characters in the file characters.txt the result should get stored inside a new folder with a txt file

Example: characters.txt: abcdefghijklmnopqerstuvwxzy

so there is 1 occurrence of g

then "1" should be stored in foulder/file.txt

 file = open(filename, "r")
 text = file.read()
 count = 0
 for char in text:
 if char == letter:
 count += 1
os.mkdir("g")
f = open("res.txt", mode = "w")
f.write(count)
f.close
asked Jun 13, 2022 at 8:23
1
  • Where do you call the function? Commented Jun 13, 2022 at 8:28

2 Answers 2

0

Your code works, but in the samples provided you dont call it.

I made a local version without your file code.

def letterFrequency(letter):
 count = 0
 for char in 'abcdefghijklmnopqerstuvwxzy':
 if char == letter:
 count += 1
 return count
print(letterFrequency('g'))

If you only want to search the first 200 character of a file you should use a while loop. Also you will need to account for rows with less than 200 characters.

answered Jun 13, 2022 at 8:41
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your response, can i make the same without a function?
sure, you just need to delete the def and return. Then you need to fix the indentation. Count will then be global so you can just use it.
I tried to specifie the range of but I didn't work. text = file.readlines()[0,119] any idea?
you can need to itterate through the rows and check the length of the rows If row 1 has 180 character you need to substrac them from you maximum and so on until you have your 200 chars
0

I modified your given example and added some improvements. The code below is a minimal working example:

import os
file = open("./Desktop/text.txt", "r")
text = file.read()
count = 0
letter = "g"
if len(text) < 200:
 text = text[0:199]
for char in text:
 if char == letter:
 count += 1
 
try: 
 os.mkdir("./Desktop/DIR")
except FileExistsError:
 print("Dir already exists")
f = open("./Desktop/DIR/res.txt", "w")
f.write(str(count))
answered Jun 13, 2022 at 8:57

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.