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.
CodePudding user response:
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