我从 Goodreads 中抓取了一堆引用,存储在 bs4.element.ResultSet
中。 ,每个元素的类型为 bs4.element.Tag
。我正在尝试将正则表达式与 python 3.6.3 中的 re 模块一起使用来清理引号并仅获取文本。当我使用 [print(q.text) for q in quotes]
进行迭代和打印时有些引用看起来像这样
“Don't cry because it's over, smile because it happened.”
―
而其他的看起来像这样:
“If you want to know what a man's like, take a good look at how he treats his inferiors, not his equals.”
―
,
每个末尾都有一些额外的空行。我的想法是我可以迭代 quotes
并调用re.match
每个报价如下:
cleaned_quotes = []
for q in quote:
match = re.match(r'“[A-Z].+$”', str(q))
cleaned_quotes.append(match.group())
我猜测我的正则表达式模式与任何内容都不匹配,因为我收到以下错误:
AttributeError: 'NoneType' object has no attribute 'group'
毫不奇怪,打印列表会给出 None
的列表。对象。关于我可能做错了什么有什么想法吗?
最佳答案
由于您出于学习目的而请求此内容,因此以下是正则表达式答案:
(?<=“)[\s\s]+?(?=”)
说明:
我们使用positive lookbehind to and lookahead标记模式的开始和结束,并同时从结果中删除引号。
在引号内,我们懒惰地将任何内容与 .+?
示例代码:
import re
regex = r"(?<=“)[\s\S]+?(?=”)"
cleaned_quotes = []
for q in quote:
m = re.search(regex, str(q))
if m:
cleaned_quotes.append(m.group())
可以说,我们不需要任何正则表达式标志。为多个匹配添加 g
|global 标志。并且 m
|multiline 逐行处理匹配(在这种情况下,可能需要使用 [\s\S]
而不是点来获取跨行结果。 )
这也将改变位置 anchors 的行为^
和 $
,匹配行尾而不是字符串。因此,在两者之间添加这些位置 anchor 是错误的。
还有一件事,我使用 re.search()
因为 re.match()
仅从字符串的开头匹配。一个常见的问题。请参阅documentation .
关于python - 正则表达式在 python 中匹配和清理引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50674031/