What am I doing? Because initially wordfreq is empty you can't assign it to wordfreq for the first time (it will raise key exception error). Do something like this code sample below: words = f.read() One way is use Counter as suggested, but to use your approach in which you want to start from empty an dict. Loop: > for word in "Hi, how are you?".replace(',', ' ').split(): Now check code example below to see what I suggested: > "Hi, how are you?".split() The method str.replace(old, new) returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max. But first, to keep the answer simple I will be using replace() method. To count the frequency of words in the file, one good solution is to use regex. Except for word Hi, because split(), by default, splits by whitespaces so Hi, is kept as a single string (and obviously) you don't want that. Loop with split: > for i in "Hi, how are you?".split():Īnd it looks like something you need. Str.split(str="", num=unt(str)) method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num. To understand this, notice following code snippet: > for i in "Hi, h r u?":īecause iterating over the given string char by chars instead of word by words is not what you wanted to achieve, to iterate words by words you should use the split method/function from string class in Python. You are iterating over chars in the string instead of iterating over words in the string words. And I think you are able to read the file content in words (while usually I avoid using read() function and use for line in file_descriptor: kind of code).Īs words is a string, in for loop, for i in words: the loop-variable i is not a word but a char. (I believe this will be a good answer for a new Python learner.)įrom the comment in your code it seems like you want to improve your code. Although using Counter from the collections library as suggested by is a better approach, I am adding this answer just to improve your code.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |