python:清理字符串
我有一个这样的字符串:
somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need to .be removed '
这是我想要的结果:
somestring='in this string i have many interesting occurrences of different chars that need to be removed'
我开始手动用各种 .replace
方法去处理,但组合太多了,我觉得应该有更简单的方法。也许有现成的库可以做到这一点?
有没有人知道我该怎么清理这个字符串呢?
3 个回答
1
这段代码的作用是...
首先,它会做一些准备工作,比如设置一些变量或者初始化一些东西。接下来,它会执行一些操作,比如循环、条件判断等,来处理数据或者实现某个功能。最后,它会输出结果,或者将处理后的数据返回给调用它的地方。
总的来说,这段代码就是在做一系列的步骤,来完成特定的任务。
re.sub('[\[\]/{}.,]+', '', somestring)
2
你需要做两个步骤:先去掉标点符号,然后再去掉多余的空格。
1) 使用字符串的translate方法
import string
trans_table = string.maketrans( string.punctuation, " "*len(string.punctuation)
new_string = some_string.translate(trans_table)
这个方法会用一个翻译表,把标点符号替换成空格。
2) 去掉多余的空格
new_string = " ".join(new_string.split())
19
我会使用正则表达式把所有不是字母和数字的字符替换成空格:
>>> import re
>>> somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need to .be removed '
>>> rx = re.compile('\W+')
>>> res = rx.sub(' ', somestring).strip()
>>> res
'in this string i have many interesting occurrences of different chars that need to be removed'