python中的正则表达式,从文件中读取文本

时间:2016-04-05 14:13:21

标签: python regex file match

我有正则表达式扫描html文件中的一些数据 代码正在使用 BeautifulSoup 删除 html 标记并返回以下文本(只是文本中的一部分):

/学期: 2011/1 数量: 20112222

姓名: XXXX XXXX XXXX XXXX 顾问

我的代码示例:

import re,glob,os
from bs4 import BeautifulSoup
import nltk

path = 'C:\\xampp\\htdocs\\data_tools\\transcripts'
os.chdir(path)
delch=','

def scantext(text,snum) :
    re_semstudent = re.compile("Semester:\s*(\d*)\s*\/\s*(\d)\s*Number\s*:\s*(\d{8})\s*Name\s*:\s*(.*)\s*Advisor")
    semesters = text.split("Year")

    for ind in range(1,len(semesters)):
        s = semesters[ind]
        x = re.search(re_semstudent,s)
        if x :
            year=x.group(1)
            semester=x.group(2)
            studentid=x.group(3)
            studentname=x.group(4)

        print year+"#"+semester

    return 0

ii=1
for fname in glob.glob("*.html") :
    f = open (fname)        
    text = BeautifulSoup(f.read(), 'html.parser').getText()
    scantext(text,ii)

当我尝试使用文本作为固定字符串的 re.search 时,它的工作正常! 但是当我在 scantext 函数中发送文本并使用semesters = text.split("Year")时。我可以打印每个分割的文本,但正则表达式不能匹配任何值!

1 个答案:

答案 0 :(得分:1)

您需要re.U/re.Unicode标志:

  re_semstudent = re.compile("Semester:\s*(\d*)\s*\/\s*(\d)\s*Number\s*:\s*(\d{8})\s*Name\s*:\s*(.*)\s*Advisor",re.U)

如果你追逐它会给你类似的东西:

<_sre.SRE_Match object at 0x7fe9fb721df8>
2011#1
<_sre.SRE_Match object at 0x7fe9fb721d50>
2011#2
<_sre.SRE_Match object at 0x7fe9fb721df8>
2012#1
<_sre.SRE_Match object at 0x7fe9fb721d50>
2012#2

您可能还需要使用encoding="utf-8"打开文件:

from io import open
for fname in glob.glob("*.html") :
    with open(fname, encoding="utf-8") as f:
        text = BeautifulSoup(f.read(), 'html.parser').getText()
        scantext(text, ii)