中断段落段落并动态重新排列和重新构图

时间:2019-05-13 06:53:50

标签: python

考虑一个段落

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).

我想像这样重新设置参数

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段落?

2 个答案:

答案 0 :(得分:1)

您正在寻找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

答案 1 :(得分:0)

在python3中使用随机库:

import random

def reorder(phrase):
    phrase = phrase.split('.')
    random.shuffle(phrase)

    return str.join('.', phrase) + '.'