首页 > 解决方案 > 断句并动态重排重框

问题描述

考虑一个段落,

p = "Both apples and oranges are fruits but apples are usually sweet and oranges are usually citrus.Apple have a pH arround 3 and orange between 3-4. Oranges are an excellent source of Vitamin C. Apples have a higher foliage (55mcg) as compared to oranges (23mcg).

我想重新构建 para 像,

re_order = "Apple have a pH arround 3 and orange between 3-4.Both apples and oranges are fruits but apples are usually sweet and oranges are usually citrus.Apples have a higher foliage (55mcg) as compared to oranges (23mcg).Oranges are an excellent source of Vitamin C."

如何使用python转换p为段落?re_order

标签: python

解决方案


您正在寻找random.shuffle()方法。那是随机混合一个列表。这里有一个例子:

# Import module
import random as rd

# Your string sentence
p = "Both apples and oranges are fruits but apples are usually sweet and oranges are usually citrus.Apple have a pH arround 3 and orange between 3-4. Oranges are an excellent source of Vitamin C. Apples have a higher foliage(55mcg) as compared to oranges(23mcg)."

# Slice p in list of sentence (every '.')
p_list = p.split(".")
print(p_list)
# ['Both apples and oranges are fruits but apples are usually sweet and oranges are
# usually citrus', 'Apple have a pH arround 3 and orange between 3-4', ' Oranges are an 
# excellent source of Vitamin C', ' Apples have a higher foliage(55mcg) as compared
# to oranges(23mcg)', '']

# Change the order
rd.shuffle(p_list)
print(p_list)
# [' Oranges are an excellent source of Vitamin C', ' Apples have a higher foliage(55mcg)
# as compared to oranges(23mcg)', '', 'Both apples and oranges are fruits but apples are 
# usually sweet and oranges are usually citrus', 'Apple have a pH arround 3 and orange 
# between 3-4']

# Rebuild the list as one string
p = '. '.join(p_list)
print(p)
# Oranges are an excellent source of Vitamin C.  Apples have a higher foliage(55mcg) as 
# compared to oranges(23mcg). . Both apples and oranges are fruits but apples are usually 
# sweet and oranges are usually citrus. Apple have a pH arround 3 and orange
# between 3-4


推荐阅读