【问题标题】:Regular expressions in python where text is read from filepython中的正则表达式,从文件中读取文本
【发布时间】:2016-07-25 13:02:17
【问题描述】:

我有一个正则表达式,可以从 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") 时。我可以打印每个拆分的文本,但是正则表达式无法匹配任何值!

【问题讨论】:

  • 当你已经在使用 Bs4 时,为什么还要使用正则表达式来解析 html?使用标签得到你想要的不是更容易吗?
  • 是的,没有标签会更容易,但这不是问题,因为正则表达式可以正确处理文本。也许问题在于我如何读取文件,但我不知道
  • 也许可以分享一些 html 并解释您想要获得的内容,这样会更容易提出建议。您可以将 re.compile 与 bs4 结合使用,所以我仍然认为这一切都可以使用 bs4 完成
  • dropbox.com/s/j3o54fyez14es0c/201122.html?dl=0 这是一个 html,我正在尝试从 html 中提取所有信息并将它们保存在 csv 文件中。实际上,实际的 python 脚本之前在 Mac 上使用“text = nltk.clean_html(f.read())”工作,但在 Windows 中我收到 nltk 错误,所以我使用 bs4 然后我遇到了这个问题。
  • 你真正想从 html 中得到什么?

标签: python regex file match


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-28
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多