【问题标题】:Using regex to detect words that might have an apostrophe, encoded in ASCII?使用正则表达式检测可能带有撇号的单词,用 ASCII 编码?
【发布时间】:2020-01-28 19:46:23
【问题描述】:

在 Python 中工作,我正在尝试创建一个函数,该函数将股票代码作为字符串接收,并使用从 Yahoo! 抓取的 html 数据返回公司名称。金融。除了包含撇号的公司之外,我已经让它适用于所有公司。我检查了 html 代码,发现撇号是这样编码的——我很确定它是用 ASCII 编码的。下面是修改后的 html 代码:

 html = '<!DOCTYPE html><html id="atomic" class="NoJs featurephone" lang="en-US"><head prefix="og: http://ogp.me/ns#"><script>window.performance && window.performance.mark && window.performance.mark(\'PageStart\');</script><meta charset="utf-8"/><title>Dick&#x27;s Inc (DKS) Company Profile &amp; Facts'

我想要返回的是“Dick's”。我得到的只是“迪克”。我正在使用 re 模块和 re.search。这是我的代码:

 company_name = (re.search(r'(?<=</script><meta charset="utf-8"/><title>)\w+', html).group(0))

我尝试包含撇号以确保它不会停在那里,但由于它不是 html 代码的一部分,所以它在任何地方都找不到它。我应该使用 re.search 以外的东西吗?我研究了 re.findall 但这并不能解决我查找和包含“'”的问题,而是以撇号的形式出现。

【问题讨论】:

    标签: python html regex text ascii


    【解决方案1】:

    确定您不想要Dick's, Inc (DKS) 或其他内容?只是想知道您是否按预期获得了全名。要获得Dick's,您需要取消转义您的 HTML,然后更改您的正则表达式。新的将按顺序查找一个或多个单词字符或撇号。

    import html
    
    html_string = '<!DOCTYPE html><html id="atomic" class="NoJs featurephone" lang="en-US"><head prefix="og: http://ogp.me/ns#"><script>window.performance && window.performance.mark && window.performance.mark(\'PageStart\');</script><meta charset="utf-8"/><title>Dick&#x27;s Inc (DKS) Company Profile &amp; Facts'
    html_string = html.unescape(html_string)
    company_name = (re.search(r'(?<=</script><meta charset="utf-8"/><title>)[\w\']+', html_string).group(0))
    

    结果:

    "Dick's"
    

    【讨论】:

    • 谢谢!不难,但是有没有办法使用 re 库来逃避?我应该指定的,这是一个我们可以使用的项目受到限制。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多