0

Goal: print() sentence, from long text, based on phrase.

I can split a fullstop, sentence = sentence.split('.').

Code 1:

phrase = 'PHRASE'

sentence = "Foo. My sentence contains PHRASE here. Bar."
sentence = sentence.split('.')

print(sentence)

Output:

['Foo', ' My sentence contains PHRASE here', ' Bar', '']

Now, I need to be able to have this work for any and all sentence types: . ! ?. Then extract element from list that contains phrase.

Code 2:

phrase = 'PHRASE'

sentence = "Foo. My sentence contains PHRASE here. Bar."
sentence = sentence.split('.')
sentence = [s for s in sentence if phrase in s]
sentence = sentence[0]
print(sentence)

Traceback:

Traceback (most recent call last):
  File "/usr/lib/python3.8/py_compile.py", line 144, in compile
    code = loader.source_to_code(source_bytes, dfile or file,
  File "<frozen importlib._bootstrap_external>", line 846, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./prog.py", line 16
    sentence = lambda sentence : for s in enumerate(sentence): if phrase in s: return s
                                 ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.8/py_compile.py", line 150, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 16
    sentence = lambda sentence : for s in enumerate(sentence): if phrase in s: return s
                                 ^
SyntaxError: invalid syntax

Desired Output:

My sentence contains PHRASE here.

Please let me know if there is anything else I can add to post.

StressedBoi69420
  • 1,376
  • 1
  • 12
  • 40
  • 2
    `split` only takes one delimiter - but your syntax error is cos your lambda is wrong. Regex will work instead of split - see this: https://stackoverflow.com/questions/1059559/split-strings-into-words-with-multiple-word-boundary-delimiters – doctorlove Nov 29 '21 at 14:02

1 Answers1

1

Replaced lambda with list-comprehension.

Used str.replace('?', '.').

Code:

phrase = 'PHRASE'

sentence = "Foo! My sentence contains PHRASE here! Bar?"
sentence = sentence.replace('!', '.')
sentence = sentence.replace('?', '.')
sentence = sentence.split('.')
sentence = [s for s in sentence if phrase in s]
sentence = sentence[0]
print(sentence)

Traceback:

My sentence contains PHRASE here
StressedBoi69420
  • 1,376
  • 1
  • 12
  • 40