May-13-2024, 04:04 AM
What is this supposed to do?
Class Analysis should be class Analysis. class with lower case 'c', not capital 'C'.
When declaring a class you don't have to specify the superclass when the superclass is object. class Analysis(): is fine. No need for class Analysis(object):.
Indentation is important in Python, it is how you define a block of code. I think your indentation is wrong for the return statement here:
class textanalysis(object):It looks like the start of a class, but there is no code that follows the class declaration. Where are the methods for class textanalysis?
Class Analysis should be class Analysis. class with lower case 'c', not capital 'C'.
When declaring a class you don't have to specify the superclass when the superclass is object. class Analysis(): is fine. No need for class Analysis(object):.
Indentation is important in Python, it is how you define a block of code. I think your indentation is wrong for the return statement here:
for word in set(mots): #set est utiliser pour qu'il n'y ait pas de repetitions dico[word] = self.fmt.count(word) return dico # Should be indented same as forYour class is odd. I would put the counting in __init__(), like this:
class Analysis(): """Count word occurrances in text.""" def __init__(self, text): words = "".join((c for c in text if c not in ".,?!")).lower().split() self.total = len(words) self.word_counts = {} for word in words: self.word_counts[word] = self.word_counts.get(word, 0) + 1 def most_common(self): """Return list of (word, count) tuples sorted in decreasing order.""" words = [(word, count) for word, count in self.word_counts.items()] words.sort(key=lambda x: x[1], reverse=True) return words @property def words(self): """Return list of words in text.""" return list(self.word_counts) def count(self, word): """Return count for a word.""" return self.word_counts.get(word, 0) def frequency(self, word): """Return frequency for a word""" return self.count(word) / self.total text = """I'm blue Da ba dee da ba di Da ba dee da ba di Da ba dee da ba di Da ba dee da ba di Da ba dee da ba di Da ba dee da ba di Da ba dee da ba di""" x = Analysis(text) print(x.words, x.total) print(x.word_counts) print(x.most_common()) print(x.count("ba")) print(x.frequency("ba"))
Output:["i'm", 'blue', 'da', 'ba', 'dee', 'di'] 44
{"i'm": 1, 'blue': 1, 'da': 14, 'ba': 14, 'dee': 7, 'di': 7}
[('da', 14), ('ba', 14), ('dee', 7), ('di', 7), ("i'm", 1), ('blue', 1)]
14
0.3181818181818182
Much of what was done above could be done using a Counter dictionary.