1

I'm trying to create a function which prints the number of characters whose frequency is above a threshold value... (n needs to be a single non-negative number)

import urllib
txt = urllib.urlopen("http://students.informatics.unimelb.edu.au/~ivow/info1dev/mywork/info1media/data/moby.txt").read()
tally = {}
for char in txt:
 if char in tally:
 tally[char] += 1
 else:
 tally[char] = 1
char = 'b'
def freq_threshold(n):
 if tally[char] > n:
 return tally[char]
freq_threshold(3)

I want my function to return the tally of the number of times char appears in the text only if the tally is greater than my freq_threshold(n). Currently, it returns nothing..

asked Apr 9, 2014 at 0:49
3
  • the function doesn't return anything Commented Apr 9, 2014 at 0:53
  • In general, you should explain your exact problem in the body of your question. Commented Apr 9, 2014 at 0:53
  • Thanks, I have edited my post. I know there are easier ways to do what I'm trying to accomplish, but why isn't my functioning returning a number? In the URL I used b occurs 9 times... Commented Apr 9, 2014 at 1:02

1 Answer 1

2

The function doesn't return anything because, the count of b is lesser than the threshold. In that case, it will return None by default. Anyway, you need to print the returned value like this

print freq_threshold(3)

but if you want to display all the characters whose count is greater than the threshold, then you need to iterate the dictionary like this

def freq_threshold(n):
 return [(char, tally[char]) for char in tally if tally[char] > n]

This will print all the characters whose count is greater than 3, along with the actual count itself.

Anyway, a better way to solve your problem would be to use collections.Counter and accepting the count of the character to be checked as well as a parameter, like this

import urllib, collections
txt = urllib.urlopen("http://www.blahblahblah.com").read()
tally = collections.Counter(txt)
def freq_threshold(char, n):
 if tally[char] > n:
 return tally[char]
print freq_threshold('b', 3)

Note: You need to specify the protocol being used in the urlopen call.

answered Apr 9, 2014 at 0:52
Sign up to request clarification or add additional context in comments.

1 Comment

@ZoeIngrid I am getting 9, are you printing the returned value, like I have shown in my answer?

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.