gpt4 book ai didi

python - 删除附加到单词的所有数字 - Python

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:55 24 4
gpt4 key购买 nike

我有一个像

这样的字符串
'Dogs are highly5 variable12 in1 height and weight. 123'

我想得到

'Dogs are highly variable in height and weight. 123'

我该怎么做?

这是我现有的代码:

somestr = 'Dogs are highly5 variable12 in1 height and weight. 123'

for i, char in enumerate(somestr):
if char.isdigit():
somestr = somestr[:i] + somestr[(i+1):]

但它返回

'Dogs are highly variable1 n1 hight and weight. 123'

最佳答案

给定

import string


s = "Here is a state0ment with2 3digits I want to remove, except this 1."

代码

def remove_alphanums(s):
"""Yield words without attached digits."""
for word in s.split():
if word.strip(string.punctuation).isdigit():
yield word
else:
yield "".join(char for char in word if not char.isdigit())

演示

" ".join(remove_alphanums(s))
# 'Here is a statement with digits I want to remove, except this 1.'

详情

我们使用生成器生成独立数字(带或不带标点符号)或通过 generator expression 过滤的单词.

关于python - 删除附加到单词的所有数字 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57331678/

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