python取文本中间
可以使用正则表达式来实现。例如,如果要从字符串中提取两个关键字之间的文本,可以使用以下代码:
import re
text = "This is some text with a keyword in the middle and another keyword."
keyword1 = "keyword"
keyword2 = "another"
pattern = re.compile(f"{keyword1}(.+?){keyword2}")
result = pattern.search(text)
if result:
extracted_text = result.group(1)
print(extracted_text)
else:
print("Keywords not found in text.")
这个代码块将从text字符串中查找关键字keyword和another之间的文本,并将其打印到控制台上。如果没有找到关键字,则会输出“Keywords not found in text.”。
原文地址: https://www.cveoy.top/t/topic/bMAV 著作权归作者所有。请勿转载和采集!