Created
March 27, 2019 17:12
-
-
Save victor-iyi/a34d62c725e9dbd22d3f426eb72c4e55 to your computer and use it in GitHub Desktop.
A simple iterable sentence class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Sentence(str): | |
"""A simple iterable sentence class. | |
Methods: | |
def __init__(self, text): ... | |
def __repr__(self): ... | |
def __str__(self): ... | |
def __len__(self): ... | |
def __getitem__(self, index): ... | |
def __iter__(self): ... | |
def __next__(self): ... | |
Attributes: | |
sentence (str): Sentence as raw text. | |
words (List[str]): List of words in sentence. | |
See Also: | |
Built-in `str`. | |
Example: | |
```python | |
>>> text = "This is an example sentence" | |
# Initializing a sentence object. | |
>>> sentence = Sentence(text) | |
>>> # Getting list of words in the sentence. | |
>>> sentence.words | |
['This', 'is', 'an', 'example', 'sentence'] | |
>>> # Print object representation of sentence. | |
>>> sentence | |
Sentence("This is an example sentence") | |
>>> # String representation of sentece. | |
>>> print(sentence) | |
This is an example sentence | |
>>> Loop through the words in the sentence. | |
>>> for word in seentence: | |
print(word) | |
This | |
is | |
an | |
example | |
sentence | |
>>> # Getting the length of a sentence | |
>>> len(sentence) | |
27 | |
>>> # Get a letter at a given index. | |
>>> sentence[19] | |
's' | |
``` | |
""" | |
def __init__(self, text): | |
self.text = text | |
self.__words = self.text.split() | |
self.__index = 0 | |
def __repr__(self): | |
return f'Sentence("{self.text}")' | |
def __str__(self): | |
return self.text | |
def __len__(self): | |
return len(self.text) | |
def __getitem__(self, index): | |
if index >= len(self): | |
raise IndexError('Index out of range.') | |
return self.text[index] | |
def __iter__(self): | |
return self | |
def __next__(self): | |
if self.__index >= len(self.__words): | |
raise StopIteration | |
word = self.__words[self.__index] | |
self.__index += 1 | |
return word | |
@property | |
def words(self): | |
return self.__words | |
@property | |
def sentence(self): | |
return self.text | |
@sentence.setter | |
def sentence(self, text): | |
self.text = text | |
self.__words = self.text.split() | |
self.__index = 0 | |
def sentence_generator(text): | |
for word in text.split(): | |
yield word | |
def main(): | |
sentence = Sentence('A simple iterable sentence.') | |
print(f'sentence = "{sentence}"') | |
print(f'words = {sentence.words}') | |
for word in sentence: | |
print(word) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment