gpt4 book ai didi

python - 如何以更简洁的方式进行多个字符串替换? - Python

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

什么是进行多个 string.replace 的快速方法?我正在尝试添加空格来缩短英文单词,例如

he'll -> he 'll
he's -> he 's
we're -> we 're
we've -> we 've

我还在之前和标点符号之间添加空格:

"his majesty" ->  " his majesty " 
his; majesty -> his ; majesty

有没有更快更简洁的方法呢?对于这个目的来说有点太慢了,但我一直这样做:

def removeDoubleSpace(sentence):
sentence.replace(" ", " ")
if " " in sentence:
removeDoubleSpace(sentence)

def prepro(sentence):
sentence = sentence.replace(",", " ,")
sentence = sentence.replace(";", " ; ")
sentence = sentence.replace(":", " : ")
sentence = sentence.replace("(", " ( ")
sentence = sentence.replace("(", " ) ")
sentence = sentence.replace("‘"," ‘ ")
sentence = sentence.replace('"',' " ')
sentence = sentence.replace("'re", " 're")
sentence = sentence.replace("'s", " 's")
sentence = sentence.replace("'ll", " 'll")
sentence = removeDoubleSpace(sentence)
return sentence

最佳答案

您可以使用一些正则表达式来完成相同的任务:

import re

# Replace multiple consecutive spaces with a single space
# Example: "One Two Three Four!" -> "One Two Three Four!"
sentence = re.sub(' +', ' ', sentence)

# Surround each instance ; : ( ) ‘ and " with spaces
# Example: '"Hello;(w)o:r‘ld"' -> " Hello ; ( w ) o : r ‘ ld "
sentence = re.sub('([;:()‘"])', ' \\1 ', sentence)

# Insert a space before each instance of , 's 're and 'll
# Example: "you'll they're, we're" -> "you 'll they 're , we 're"
sentence = re.sub("(,|'s|'re|'ll)", ' \\1', sentence)

return sentence

关于python - 如何以更简洁的方式进行多个字符串替换? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12701520/

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