繁体   English   中英

返回包含搜索字符串的句子

[英]Return sentence that contains search string

目标: print()句子,来自长文本,基于短语。

我可以拆分句号, sentence = sentence.split('.')

代码 1:

phrase = 'PHRASE'

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

print(sentence)

Output:

['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

所需的 Output:

My sentence contains PHRASE here.

如果还有什么我可以添加到帖子中,请告诉我。

将 lambda 替换为list-comprehension

使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM