0

So I'm currently trying to write some code that opens and reads a text file. The text file contains a short paragraph. Within the paragraph, there are some words with brackets around them, which could look like: "the boy [past_tense_verb] into the wall." I am trying to write code that looks for the brackets in the text file, and then displays to the user the words in the text file, for the user to then write some input that will replace the bracketed words. This is the code I have so far:

f = open('madlib.txt', 'r')
for line in f:
    start = line.find('[')+1
    end = line.find(']')+1
    word = line[start:end+1]
    inputword = input('Enter a ' + word + ': ')
    print(line[:start] + inputword + line[end:])

Any help is greatly appreciated - thanks!

4
  • This code fails when there is no [past_tense_verbs] in the line, because find() returns -1 for "not found", and it's being promoted to 0. Do you need to handle the case where there is more than one bracketed word in the line? Commented Mar 1, 2019 at 1:32
  • This would be best implemented with regex. Is there a reason why you aren't using it? Commented Mar 1, 2019 at 1:33
  • @Kingsley - yes, on some of the lines, there are two bracketed words. Commented Mar 1, 2019 at 1:43
  • @blhsing - I have not learned about regex yet - care to expand your thought a little? Commented Mar 1, 2019 at 1:43

1 Answer 1

3
import re

with open('madlib.txt', 'r') as f:
    data = f.read()

words_to_replace = re.findall(r"\[(\w+)\]", data)
replace_with = []

for idx, i in enumerate(words_to_replace):
    print(f"Type here replace \033[1;31m{i}\033[1;m with:", end =" ")
    a = input()
    replace_with.append(a)

for idx, i in enumerate(replace_with):
    data = data.replace(words_to_replace[idx], i)

with open('newmadlib.txt', 'w') as f:
    f.write(data)
Sign up to request clarification or add additional context in comments.

7 Comments

The third and fourth lines are getting syntax errors at the end of their line
no worries! I just tried the new code, but am now getting an error saying 'm' is not defined, when being used in the line "for idx, i in enumerate(m):"
oops... try now
Works really well - thanks! Is there any way to ask the user like "Enter a .." and then whatever kind of word is in the bracket?
Yes. I've just replaced print(i) to print(f'Type to replace {i}:')
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.