考虑一个段落
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
段落?
答案 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) + '.'