pandas学习之字符串对象化方法,正则表达式

字符串对象化方法

val='a,b, guido'
pieces=[x.strip() for x in val.split(',')] #以逗号分隔符切割字符,并且去掉字符前后空格

first,second,third=pieces
first+"::"+second+"::"+third #连接字符,输出'a::b::guido'
等价于 .join方法
"::".join(pieces)

"guide" in pieces

#find index 的区别是: 如果找不到字符串,index将会引发一个异常, 而find返回-1

val.index(",")
val.find(":")
val.count('a')
try:
  val.index(':')
except:
    print('not fount')

val.replace(',','::')

正则表达式

#正则表达式
import re
text="foo   bar\t baz  \tqux"
re.split("\s+",text) #/s+ 表示一个或多个空格符   \t表示空格符 返回['foo', 'bar', 'baz', 'qux']

#对多个字符串都应用同一条正则表达式,使用compile把正则表达式编译下来可节省时间
regex=re.compile('\s+')
regex.split(text) #调用方法,返回['foo', 'bar', 'baz', 'qux']

#findall 返回字符串中所有匹配项,search返回第一个匹配项。match更加严格,它只匹配字符串的首部
regex.findall(text) #找到匹配regex的所有模式 ['   ', '\t ', '  \t']
text='''
Dave [email protected]
Steve [email protected]
Rob [email protected]
Ryan [email protected]
'''
patten=r'[A-Z0-9.%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'
regex=re.compile(patten,flags=re.IGNORECASE) # re.IGNORECASE 的作用是使正则表达式对大小写不敏感
regex.findall(text) #['[email protected]', '[email protected]', '[email protected]', '[email protected]']

text1=[]
for t in text.split('\n'):
    if t:
        text1.append(t)
text1
#['Dave [email protected]','Steve [email protected]', 'Rob [email protected]','Ryan [email protected]']

m = regex.search(text)
text[m.start():m.end()]  #'[email protected]'
regex.match(text) #None

n=regex.match('[email protected]')
n.groups
#将找出的模式分段,用圆括号括起来即可
pattern = r'([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})'
regex = re.compile(pattern, flags=re.IGNORECASE)
regex.findall(text)
#sub方法,将匹配到的模式替换为指定字符串,并返回新字符串
#sub可以利用\1 \2 \3访问被替换的字符串
print(regex.sub(r'Username: \1, Domain: \2, Suffix: \3', text))

regex=re.compile(r'''
(?P<username>[A-Z0-9._&+-]+)
@
(?P<domain>[A-Z0-9.-]+)
\.
(?P<suffix>[A-Z]{2,4})
''',flags=re.IGNORECASE|re.VERBOSE)
m = regex.match('[email protected]')
m.groupdict()

#{'domain': 'bright', 'suffix': 'net', 'username': 'wesm'}

pandas中矢量化的字符串函数 

#pandas中矢量化的字符串函数
data={'Dave': '[email protected]', 'Steve': '[email protected]',
        'Rob': '[email protected]', 'Wes': np.nan}
data=Series(data)
data.isnull()

#通过map,所有字符串和正则都能传入各个值(通过lambda或者其他函数),但是如果存在NA就会报错。
#然而,Series有些跳过NA的方法。通过Series的str属性可以访问这些方法
data.str.contains('gmail')
data.str.findall(patten,flags=re.IGNORECASE)
data.str.replace("@","")
matches=data.str.match(patten,flags=re.IGNORECASE)
matches.str.get(1)
matches.str[0]
data.str[:5]

猜你喜欢

转载自blog.csdn.net/qq_42052864/article/details/81662475