gpt4 book ai didi

python - 从字符串中删除所有标点符号,除非它在数字之间

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:54 25 4
gpt4 key购买 nike

我有一个包含单词和数字的文本。我将给出一个具有代表性的文本示例:

string = "This is a 1example of the text. But, it only is 2.5 percent of all data"

我想把它转换成类似的东西:

"This is a  1 example of the text But it only is  2.5  percent of all data"

因此删除标点符号(可以是. ,string.punctuation 中的任何其他符号)并放入连接时数字和单词之间的空格。但在我的示例中,请将 float 保持为 2.5。

我使用了以下代码:

item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item

结果是:

 >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"

我快到了,但无法弄清楚最后的和平。

最佳答案

您可以像这样使用正则表达式环视:

(?<!\d)[.,;:](?!\d)

Working demo

想法是让一个字符类收集您要替换的标点符号,并使用环视来匹配周围没有数字的标点符号

regex = r"(?<!\d)[.,;:](?!\d)"

test_str = "This is a 1example of the text. But, it only is 2.5 percent of all data"

result = re.sub(regex, "", test_str, 0)

结果是:

This is a 1example of the text But it only is 2.5 percent of all data

关于python - 从字符串中删除所有标点符号,除非它在数字之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43142710/

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