Created
November 1, 2022 13:16
-
-
Save pleabargain/6a758764090dd4a367d22b538d29856e to your computer and use it in GitHub Desktop.
python manipulating text variable using a list of functions as a variable
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
# very long sample text | |
text = "This is a very long sample text. It is so long that it will be used to demonstrate the use of functions as variables. It is also used to demonstrate the use of functions as arguments to other functions. It is also used to demonstrate the use of functions as return values from other functions. It is also used to demonstrate the use of functions as items in lists. It is also used to demonstrate the use of functions as items in tuples. It is also used to demonstrate the use of functions as items in dictionaries. It is also used to demonstrate the use of functions as items in sets. It is also used to demonstrate the use of functions as items in frozen sets. It is also used to demonstrate the use of functions as items in comprehensions. It is also used to demonstrate the use of functions as items in generator expressions. It is also used to demonstrate the use of functions as items in class definitions" | |
#function print all unique words in text | |
def print_unique_words(text): | |
return(set(text.split())) | |
#create a function that removes all words with less than 4 characters | |
def remove_short_words(text): | |
return ' '.join([w for w in text if len(w) >= 4]) | |
# function to remove punctuation | |
def remove_punctuation(text): | |
return ''.join([c for c in text if c not in '.,;:?!()']) | |
#create a function that removes all periods from text | |
def remove_periods(text): | |
return text.replace('.', '') | |
# function to remove all words longer than 5 characters | |
def remove_long_words(text): | |
return ' '.join([w for w in text.split() if len(w) <= 7]) | |
# create list to hold all functions | |
all_functions = [print_unique_words, | |
remove_short_words, | |
remove_punctuation, | |
remove_long_words,] | |
# create for loop to iterate through all functions | |
for f in all_functions: | |
text = f(text) | |
print(text) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment