美文网首页
Python 正则表达式查找

Python 正则表达式查找

作者: 郭青茄 | 来源:发表于2020-05-04 15:51 被阅读0次

import re

import csv

# data = open('tieba01.txt', 'r', encoding='UTF-8').readlines()

# print(len(data))

with open('tieba01.txt', 'r', encoding='UTF-8') as f:

    source= f.read()

#search函数只能从左至右找出第一个最大的匹配,findall函数可以找出所有的匹配,并返回一个list列表

# findall(pattern, string, flags=0)  re.S忽略换行

result_list= []

username_list= re.findall('username="(.*?)"',source,re.S)#

content_list= re.findall('d_post_content j_d_post_content " style="display:;">(.*?)</div>', source, re.S)

reply_time_list=re.findall('class="tail-info">(2020.*?)<', source, re.S)

def clear_content(src):

    newstr= re.sub(r'(<img class.*?>)', '', src) #sub是substitute的所写,表示替换;re.sub(pattern, repl, string, count=0, flags=0)

    return newstr

print(username_list[0],content_list[12])

for iin range(len(username_list)):

    clearstr= clear_content(content_list[i])

    result= {'username':username_list[i],

              'content':clearstr,

              'time': reply_time_list[i]}

    result_list.append(result)

with open('tieba01.csv','w',newline='',encoding='utf-8-sig') as f:

    csv_write= csv.writer(f)

    writer= csv.DictWriter(f,fieldnames=['username','content','time'])

    writer.writeheader()

    writer.writerows(result_list)

# with open('E:/dst.csv', 'wb') as dstfile:  # 写入方式选择wb,否则有空行

#    writer = csv.DictWriter(dstfile, fieldnames=['username','content','time'])

#    writer.writeheader()  # 写入表头

#    writer.writerows(data)  # 批量写入

相关文章

  • Day-15 正则表达式

    正则表达式:用来查找、匹配、切割字符串的工具 python对正则表达式的支持

  • day19-总结

    python中的正则表达式 正则表达式:用来做字符串查找,匹配,切割用的一种工具python对正则表达式的支持:提...

  • 2018-08-03 day15 正则表达式

    正则表达式:用来做字符串查找,匹配,切割的一种工具 python对正则表达式的支持:提供了re模块(python内...

  • 01-正则表达式的符号

    正则表达式:用来做字符串查找、匹配、切割用的一种工具 python对正则表达式的支持:提供了re模块(python...

  • 正则表达式

    正则表达式:用来做字符串查找,匹配,切割用的一种工具python对正则表达式的支持:提供了re模块(python内...

  • 2018-08-03 python学习正则表达式

    正则表达式:用来做字符串查找、匹配、切割用的一种工具 python对正则表达式的支持:提供了re模块(python...

  • 16-笔记整理(正则表达式)

    正则表达式: 用来做字符串查找,匹配,切割用的一种工具python对正则表达式的支持,提供了re模块(python...

  • day15总结

    一、正则表达式符号 正则表达式:字符串查找、匹配、切割(python对正则表达式的支持:提供了re模块(pytho...

  • Python学习笔记7—正则表达式之一

    用正则表达式查找文本模式 1.正则表达式,简称regex,Python中所有正则表达式的函数都在re模块中 \d...

  • day 16

    part 1 正则表达式 正则表达式:用来做字符串查找、匹配、切割的一种工具。Python对正则表达式的支持,提供...

网友评论

      本文标题:Python 正则表达式查找

      本文链接:https://www.haomeiwen.com/subject/wwhyghtx.html