I've written code for a program that reads a text file, checking if there's any capitalized parts of speech of specific types (noun, adj, verb, adv) in the text and replace them with the user's chosen word for that category.
Below is an example of how it the result should be:
Original: "The ADJECTIVE, ADJECTIVE, and ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events."
Output: "The big, bad and evil panda walked to the cafe and then slapped the employee. A nearby waiter was unaffected by these events."
It's quite lengthy. Is there anywhere in the code I can make it more succinct? Or a better way to go about this problem? Your input is much appreciated!
txt_file = open('readtext.txt')
txt_str = txt_file.read()
print(txt_str)
print()
#turn file content to list, store words to replace in a list
txt_list = txt_str.split()
replace_w = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']
def save_suffixprefix(letters):
"""return a list of non letters at
the beginning/end and reverse the list of letters provided"""
non_letters = ''
for char in letters:
if not char.isalpha():
non_letters += char
else:
break
letters.reverse()
return non_letters
for i, word in enumerate(txt_list):
letters = list(word) #get a list of char in each word to collect suffix/prefix
prefix = save_suffixprefix(letters)
suffix = save_suffixprefix(letters)
word = ''.join(letters).strip(prefix).strip(suffix) #construct a word of only letters
# checking if it's a word that needs replacing, if so, ask for input,
# reconstruct new word with prefix, suffix reattached and update the file content list
if word in replace_w:
replace_this = input(f"Enter a/an {replace_w[replace_w.index(word)]}: ")
txt_list[i] = prefix + replace_this + suffix
print()
new_ver = ' '.join(txt_list) #make file content list string again
print(new_ver)
# write to file
txt_file = open('readtext.txt', 'w')
txt_file.write(new_ver)
txt_file.close()