程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了替换 Python 文本中逗号分隔的元素位置大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决替换 Python 文本中逗号分隔的元素位置?

开发过程中遇到替换 Python 文本中逗号分隔的元素位置的问题如何解决?下面主要结合日常开发的经验,给出你关于替换 Python 文本中逗号分隔的元素位置的解决方法建议,希望对你解决替换 Python 文本中逗号分隔的元素位置有所启发或帮助;

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

 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 @R_315_10586@l assets are $1,555,`555.

在上面的字符串中,搜索/apple、banana、milk、sanDWich/movIE、music、reading/,随机改变位置。排除此处的数字 ($1,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,555.

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

解决方法

可以先提取逗号分隔的值,拆分,然后使用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 @R_315_10586@l assets are $1,555,555.
"""
vals,base,r = re.findall('(?:[\$\w]+,\s*\w+)+(?:,\s*\w+)*|\w+,',s),re.sub('(?:[\$\w]+,'{}',[]
for val in vals:
   if not val.startswith('$') and len(re.split(',\s*',val)) > 2:
      new_vals = re.split(',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,555.

大佬总结

以上是大佬教程为你收集整理的替换 Python 文本中逗号分隔的元素位置全部内容,希望文章能够帮你解决替换 Python 文本中逗号分隔的元素位置所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Python替换