【问题标题】:Replace comma-separated element positions inside Python text替换 Python 文本中逗号分隔的元素位置
【发布时间】:2021-04-20 03:34:44
【问题描述】:

我试图在文本中找到一个逗号分隔的值并随机更改位置。例如

 Good morning. I am James. The weather is very nice today. I ate apples, bananas, milk, sandwich this morning. 

And my favorite things are movies, music, read books. And my total assets are $1,555,555,`555.

在上面的字符串中,搜索/apple、banana、milk、sandwich/movie、music、reading/并随机更改位置。在此处排除数字(1,555,555,555 美元)。所以终于

Good morning. I am James. The weather is very nice today. I ate bananas, apples, sandwiches, milk this morning.

And my favorite things are music, movies, read books. And my total assets are $1,555,555,555.

我想这样改。元素应该随机变化。

【问题讨论】:

  • 到目前为止你尝试过什么? SO 不是代码编写服务。
  • 对不起,我是初学者,所以我不知道该怎么做。我搜索了,但没有找到类似的东西

标签: python string random split


【解决方案1】:

可以先提取逗号分隔的值,拆分,然后使用random.shuffle

import random, re
s = """
Good morning. I am James. The weather is very nice today. I ate apples, bananas, milk, sandwich this morning. 

And my favorite things are movies, music, read books. And my total assets are $1,555,555,555.
"""
vals, base, r = re.findall('(?:[\$\w]+,\s*\w+)+(?:,\s*\w+)*|\w+,', s), re.sub('(?:[\$\w]+,\s*\w+)+(?:,\s*\w+)*|\w+,', '{}', s), []
for val in vals:
   if not val.startswith('$') and len(re.split(',\s*', val)) > 2:
      new_vals = re.split(',\s*', val)
      random.shuffle(new_vals)
      r.append(', '.join(new_vals))
   else:
      r.append(val)

new_string = base.format(*r)

输出:

Good morning. I am James. The weather is very nice today. I ate bananas, apples, sandwich, milk this morning. 

And my favorite things are music, movies, read books. And my total assets are $1,555,555,555.

【讨论】:

  • 谢谢。很好。但是,是否只有在三个或更多元素用逗号分隔时才能使其工作(例如元素 1、元素 2、元素 3)?如果有两个就行,即使句子中只有一个逗号,句子也会变形,句子会很别扭。
  • @anfwkdrn 你能举个例子说明你的意思吗?
  • """abc1, abcdefgh abcdefgh abcdefgh abc2, abc2, abc2 abcdefgh abcdefgh abc3, abc3, abc3, abc3 abcdef """ 表示像abc1这样有一个逗号时不起作用,而仅当有两个或多个逗号(如 abc2 和 abc3)时才有效。
  • @anfwkdrn 很高兴为您提供帮助!
  • @anfwkdrn 如果您想进一步测试正则表达式的范围,我建议您查看regex101
猜你喜欢
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 2014-03-11
  • 2017-10-01
  • 2016-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多