在python中,如何用空格替换所有这些特殊字符?

2024-05-15 10:35:15 发布

您现在位置: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

有人能帮我吗?


Tags: mastertxtmy公司oldcompanyincpvt
3条回答
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
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'

假设您打算更改所有非字母数字的内容,可以在命令行上执行此操作:

cat foo.txt | sed "s/[^A-Za-z0-99]/ /g" > bar.txt

或者在带有re模块的Python中:

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)

相关问题 更多 >