按关键字提取的句子的输出



我是Python的新手。我很难通过几个关键词弄清楚提取句子的格式。摘录了几句话。如何将几个句子的输出转换为一个字符串?

例如:

search_keywords=['my family','love my']
text = "my family is good. I love my family. I am happy."
sentences = text.split(".")
for sentence in sentences:
if (any(map(lambda word: word in sentence, search_keywords))):  
print (sentence)
count = len(sentence.split()) 
print(count)

输出为:

my family is good
4
I love my family
4

如何将两个提取的句子组合成一个字符串,使总数等于 8,如下所示:

my family is good. I love my family. 
8

任何帮助,不胜感激。

让我纠正你的python代码

#your data
search_keywords=['my family','love my']
text = "my family is good. I love my family. I am happy."
sentences = text.split(".")
#initialise
total_count = 0
final_sentence = ""
#every sentences
for sentence in sentences:
if (any(map(lambda word: word in sentence, search_keywords))):  
#add the count to total_count
total_count += len(sentence.split()) 
#add the sentence to final sentence
final_sentence += sentence+'.'
#print the final_sentence and total_count
print(final_sentence)
print(total_count)

这个怎么样:

result = []
result_count = 0
for sentence in sentences:
if (any(map(lambda word: word in sentence, search_keywords))):  
result.append(sentence)
result_count += len(sentence.split())
print('. '.join(result) + '.')
print(result_count)
#my family is good.  I love my family.
#8

对字符串使用join方法:

outp = []
count = 0
for sentence in sentences:
if (any(map(lambda word: word in sentence, search_keywords))):  
outp.append(sentence)
count += len(sentence.split()) 
print('. '.join(outp) + '.')
print(count)

选择分隔符字符串并应用join方法,提供要由字符串分隔的列表。

最新更新