【问题标题】:Finding a regex patterned text inside a python variable在 python 变量中查找正则表达式模式文本
【发布时间】:2017-02-15 18:08:04
【问题描述】:
    # Ex1
    # Number of datasets currently listed on data.gov
    # http://catalog.data.gov/dataset


    import requests
    import re

    from bs4 import BeautifulSoup


    page = requests.get(
        "http://catalog.data.gov/dataset")

    soup = BeautifulSoup(page.content, 'html.parser')

    value = soup.find_all(class_='new-results')

    results = re.search([0-9][0-9][0-9],[0-9][0-9][0-9], value


    print(value)

代码在上面..我想在 regex = [0-9][0-9][0-9],[0-9][0-9][0- 9]

在变量'value'内的文本内

我该怎么做?

根据ShellayLee的建议,我将其更改为

import requests
import re

from bs4 import BeautifulSoup


page = requests.get(
    "http://catalog.data.gov/dataset")

soup = BeautifulSoup(page.content, 'html.parser')

value = soup.find_all(class_='new-results')

my_match = re.search(r'\d\d\d,\d\d\d', value)


print(my_match)

仍然出现错误

Traceback(最近一次调用最后一次): 文件“ex1.py”,第 19 行,在 my_match = re.search(r'\d\d\d,\d\d\d', 值) 搜索中的文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py”,第 182 行 return _compile(pattern, flags).search(string) TypeError:预期的字符串或类似字节的对象

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    您需要一些 Python 正则表达式的基础知识。 Python 中的正则表达式表示为字符串,re 模块提供了诸如matchsearchfindall 之类的函数,它们可以将字符串作为参数并将其视为模式。

    在您的情况下,模式[0-9][0-9][0-9],[0-9][0-9][0-9] 可以表示为:

    my_pattern = r'\d\d\d,\d\d\d'
    

    然后像这样使用

    my_match = re.search(my_pattern, value_text)
    

    其中\d 表示数字符号(与[0-9] 相同)。 r 引导字符串意味着字符串中的反斜杠不被视为转义符。

    搜索函数返回match object


    我建议您先浏览一些教程,以消除进一步的困惑。官方的 HOWTO 已经写得很好了:

    https://docs.python.org/3.6/howto/regex.html

    【讨论】:

    • @BinuAlexander 如果您觉得这个答案有帮助,请给我点赞:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    相关资源
    最近更新 更多