findall() returns html 文件中的空字符串 Python REGEX

findall() returns empty string on html file in Python REGEX

我正在使用 Python 学习正则表达式,并且正在做 Google 正则表达式教程中的婴儿名字练习。 html 文件 --baby1990.html-- 是一个压缩文件,可以在这里下载:https://developers.google.com/edu/python/set-up ('Download Google Python Exercises')

年份放在标签中。 html 代码如下:

<h3 align="center">Popularity in 1990</h3>

我正在使用以下代码从文件中提取年份:

f = open('C:/Users/ALEX/MyFiles/JUPYTER NOTEBOOKS/google-python-exercises/babynames/baby1990.html', 'r')

strings = re.findall(r'<h3 align="center">Popularity in (/d/d/d/d)</h3>', f.read())

我已经在 RegularExpressions101 网站上测试了该模式并且它有效。

但是返回的 'strings' 列表是空的。

len(字符串) 出来

我认为在上下文字符串中匹配年份的最佳方法是使用 re.search or re.match.

例如:

import re

tag = """<h3 align="center">Popularity in 1990</h3>"""

mo = re.search(r"Popularity in (\d{4})", tag)
year = mo.group(1) if mo else ""

print(year)
# -> 1990

或者当然,如果你想找到所有的匹配项,你需要使用re.findall

你检查你的 Python 正则表达式,你也可以在线尝试 https://regex101.com/