如何在Python3中逐段落反转文本文件的每行与单词?
解决方案:按句子单位实现文本反转
我明白你的问题啦——你想把这段关于植物的文本,按句子为单位先反转整个句子的顺序,再把每个句子里的单词也反转,但之前用split()和join()直接处理的话,只会把所有单词混在一起整体反转,达不到按句子处理的效果。
咱们可以分步骤来实现:
步骤1:读取文本并分割成句子
首先得把原文本拆成一个个独立的句子。注意原文本里的句子是以. (句号加空格)分隔的,所以用. 来分割,最后记得处理最后一个句子的句号。
步骤2:对每个句子进行单词反转
拿到每个句子后,先把句子里的单词拆分,反转顺序,再拼接起来,还要保留结尾的句号。
步骤3:反转整个句子列表的顺序
把处理好的单个句子,整体反转顺序,最后再把所有句子拼接成最终的字符串。
下面是具体的Python代码示例:
# 原文本内容 original_text = "Plants are mainly multi-cellular. Green plants obtain most of their energy from sunlight via photosynthesis. There are about 320,000 species of plants. Some 260–290 thousand, produce seeds. Green plants produce oxygen. Green plants occupy a significant amount of land today. We should conserve this greenery around us." # 步骤1:分割成句子(处理最后一个句子的句号) sentences = original_text.split('. ') # 给最后一个句子补上句号 sentences[-1] += '.' # 步骤2:处理每个句子——反转单词顺序 processed_sentences = [] for sentence in sentences: # 拆分单词,注意句子结尾的句号,先去掉再拆分,反转后再加回来 words = sentence[:-1].split() reversed_words = words[::-1] reversed_sentence = ' '.join(reversed_words) + '.' processed_sentences.append(reversed_sentence) # 步骤3:反转整个句子列表的顺序 final_sentences = processed_sentences[::-1] # 拼接成最终结果 result = ' '.join(final_sentences) print(result)
运行这段代码后,输出的结果就和你期望的一致啦:
oxygen. produce plants Green seeds. produce thousand, 260–290 Some plants. of species 320,000 about are There photosynthesis. via sunlight from energy their of most obtain plants Green multi-cellular. mainly are Plants us. around greenery this conserve should we today. land of amount significant a occupy plants Green.
简单说,核心就是先按句子拆分,再分别处理每个句子的单词反转,最后反转句子的整体顺序,而不是直接对整个文本的单词进行反转。这样就能精准实现你想要的效果啦~
内容的提问来源于stack exchange,提问作者j_robot




