gpt4 book ai didi

python - 替换字符串中的多个元素

转载 作者:行者123 更新时间:2023-11-28 22:22:41 25 4
gpt4 key购买 nike

我正在学习中级 python。

假设有一个字符串

astring = '[Embodied cognition - Wikipedia](https://en.wikipedia.org/wiki/Embodied_cognition)'

使用 string.punctuation 提取单词

from string import punctuation
for delimiter in punctuation:
if delimiter in astring:
astring = astring.replace(delimiter, ' ')

In [7]: astring
Out[7]: ' Embodied cognition Wikipedia https en wikipedia org wiki Embodied cognition '

我尝试使用 map 并且它有效

In [12]: a = map(astring.replace, punctuation, ' ')
In [14]: list(a)
Out[14]: [' Embodied cognition Wikipedia https en wikipedia org wiki Embodied cognition ']

如何用其他先进技术解决这个问题?

最佳答案

您应该查看正则表达式(简称 regex)。

import re

astring = '[Embodied cognition - Wikipedia](https://en.wikipedia.org/wiki/Embodied_cognition)'
re.sub(r'[^A-Za-z0-9]+', ' ', astring)
# returns:
' Embodied cognition Wikipedia https en wikipedia org wiki Embodied cognition '

关于python - 替换字符串中的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47523313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com