前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 过滤字母和数字实例1实例 2实例 3

Python 过滤字母和数字实例1实例 2实例 3

作者头像
致Great
发布2018-06-13 14:56:28
2.4K0
发布2018-06-13 14:56:28
举报
文章被收录于专栏:程序生活程序生活程序生活

实例1

crazystring = 'dade142.!0142f[., ]ad'

# 只保留数字
new_crazy = filter(str.isdigit, crazystring)
print(''.join(list(new_crazy)))
# 只保留字母
new_crazy = filter(str.isalpha, crazystring)
print(''.join(list(new_crazy)))


# 只保留字母和数字
new_crazy = filter(str.isalnum, crazystring)
print(''.join(list(new_crazy)))

# 如果想保留数字0-9和小数点’.’ 则需要自定义函数

new_crazy = filter(lambda ch: ch in '0123456789.', crazystring)
print(''.join(list(new_crazy)))

实例 2

1.正则表达式

import re
L = ['小明', 'xiaohong', '12', 'adf12', '14']
for i in range(len(L)):
    if re.findall(r'^[^\d]\w+', L[i]):
        print(re.findall(r'^\w+$', L[i])[0])
  1. 避开正则表达式
L = ['xiaohong', '12', 'adf12', '14', '晓明']
for x in L:
    try:
        int(x)
    except:
        print(x)
  1. 使用string内置方法
L = ['xiaohong', '12', 'adf12', '14', '晓明']

# 对于python3来说同样还可以使用string.isnumeric()方法
for x in L:
    if not x.isdigit():
        print(x)
# for x in L:
#     if not x.isnumeric():
#         print(x)

实例 3

要进行中文分词,必须要求数据格式全部都是中文,需求过滤掉特殊符号、标点、英文、数字等。当然了用户可以根据自己的要求过滤自定义字符。

import re
x = 'a12121assa'
x = '1我爱你1'
r1 = '[a-zA-Z0-9’!"#$%&\'()*+,-./:;<=>?@,。?★、…【】《》?“”‘’![\\]^_`{|}~]+'

print(re.sub(r1, '', x))

来自 https://blog.csdn.net/xiaodongxiexie/article/details/56683433 https://www.cnblogs.com/alaska1131/articles/1607239.html

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.05.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实例1
  • 实例 2
  • 实例 3
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档