如何在Python中用空格替换所有特殊字符?
如何在Python中把所有特殊字符替换成空格?
我有一份公司的名字列表……
例如:-[myfiles.txt]
MY company.INC
Old Wine pvt
master-minds ltd
"apex-labs ltd"
"India-New corp"
Indo-American pvt/ltd
根据上面的例子……我需要把文件myfiles.txt中的所有特殊字符[-,",/,.]替换成一个空格,并保存到另一个文本文件myfiles1.txt中。
有没有人能帮我一下?
相关问题:
5 个回答
4
在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解和使用这些数据,我们需要将它们转换成程序能识别的格式。
比如说,如果你有一个数字的字符串“123”,程序可能会把它当作文本来处理,而不是数字。为了让程序能进行数学运算,我们需要把这个字符串转换成数字。这种转换的过程就叫做“类型转换”。
在不同的编程语言中,类型转换的方法可能会有所不同。有些语言会自动帮你转换,有些则需要你手动指定。了解这些转换的方法,可以帮助你更好地处理数据,让程序运行得更顺利。
import re
strs = "how much for the maple syrup? $20.99? That's ricidulous!!!"
strs = re.sub(r'[?|$|.|!]',r'',strs) #for remove particular special char
strs = re.sub(r'[^a-zA-Z0-9 ]',r'',strs) #for remove all characters
strs=''.join(c if c not in map(str,range(0,10)) else '' for c in strs) #for remove numbers
strs = re.sub(' ',' ',strs) #for remove extra spaces
print(strs)
Ans: how much for the maple syrup Thats ricidulous
5
import string
specials = '-"/.' #etc
trans = string.maketrans(specials, ' '*len(specials))
#for line in file
cleanline = line.translate(trans)
>>> line = "Indo-American pvt/ltd"
>>> line.translate(trans)
'Indo American pvt ltd'
例如:
16
假设你是想把所有非字母数字的字符都替换掉,你可以在命令行中这样做:
cat foo.txt | sed "s/[^A-Za-z0-99]/ /g" > bar.txt
或者你也可以在Python中使用 re 模块来实现:
import re
original_string = open('foo.txt').read()
new_string = re.sub('[^a-zA-Z0-9\n\.]', ' ', original_string)
open('bar.txt', 'w').write(new_string)