![](/img/trans.png)
[英]remove all nonalphanumeric characters from a file and save it with the same name in python
[英]How to remove nonalphanumeric character in python but keep some special characters
我想出了如何使用以下函数在python中删除特殊的非字母数字字符:
p_nonalphanum = re.compile('\W+')
def removeNonAlphaNum(string):
m = p_nonalphanum.match(string)
if m:
string = string[m.end():]
return string
我想保留一些特殊字符,例如½,¾,我认为它们是数字。 我应该如何编辑我的正则表达式?
例如:从 “•½杯面粉” 到 “ 1/2杯面粉”
您可以使用否定的字符类并添加要保留的所有字符
你可以这样做:
p_nonalphanum = re.compile('[^\w½¾]+')
print (p_nonalphanum.sub('', test))
不用在需要手动添加每个字符的正则表达式上打扰,请使用内置的isalnum
函数!
>>> s = "• ½ cup flour -> ½ cup flour"
>>> def only_alphanum(s):
... s = unicode(s, "utf-8")
... return ' '.join(c for c in s.split() if c.isalnum())
...
>>> print only_alphanum(s)
½ cup flour ½ cup flour
这将使您可以捕获任何分数,而不仅仅是捕获在正则表达式中汇编的分数列表(该列表很快就会变长)
>>> s = "• ¼ cup oats -*(*&!!"
>>> print only_alphanum(s)
¼ cup oats
>>> def remove_unwanted(s):
... '''• ½ cup flour -> ½ cup flour'''
... allowed = '[\w½¾]+'
... return ' '.join(re.findall(allowed, s))
...
>>> print remove_unwanted('• ½ cup flour ->')
½ cup flour
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.