目標:print()句子,來自長文本,基于短語。
我可以拆分一個句號,sentence = sentence.split('.')。
代碼 1:
phrase = 'PHRASE'
sentence = "Foo. My sentence contains PHRASE here. Bar."
sentence = sentence.split('.')
print(sentence)
輸出:
['Foo', ' My sentence contains PHRASE here', ' Bar', '']
現在,我需要能夠對任何和所有句子型別進行這項作業:
. ! ?. 然后從包含phrase.
代碼 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 (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
期望輸出:
My sentence contains PHRASE here.
如果還有什么我可以添加到帖子中,請告訴我。
uj5u.com熱心網友回復:
用list-comprehension替換了 lambda 。
用過str.replace('?', '.')。
代碼:
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)
追溯:
My sentence contains PHRASE here
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370925.html
