gpt4 book ai didi

regex - 如何从 requests.get().text 中排除换行符

转载 作者:行者123 更新时间:2023-12-01 13:36:02 26 4
gpt4 key购买 nike

我正在尝试从站点响应中删除数字 http://app.lotto.pl/wyniki/?type=dl代码如下

import requests
import re

url = 'http://app.lotto.pl/wyniki/?type=dl'
p = re.compile(r'[^\d{4}\-\d{2}\-\d{2}]\d+')

response = requests.get(url)
data = re.findall(p, response.text)
print(data)

但不是 ['7', '46', '8', '43', '9', '47']我得到 ['\n7', '\n46', '\n8', '\n43', '\n9', '\n47']我怎样才能摆脱 "\n"

最佳答案

您的正则表达式不合适,因为 [^\d{4}\-\d{2}\-\d{2}]\d+匹配除数字以外的任何字符,{ , 4 , } , - , 2然后是一位或多位数字。换句话说,您将一个序列 变成了一个字符集。而那个否定字符类 可以匹配一个换行符。它也可以匹配任何字母。还有更多。 <强> strip在其他情况下无济于事,您需要修复正则表达式。

使用

r'(?<!-)\b\d+\b(?!-)'

参见 regexIDEONE demo

此模式将匹配前面没有连字符 (\d+) 或任何单词字符 ((?<!-)) 并且后面没有单词字符 (\b) 或一个连字符 ( \b )。

您的代码将如下所示:

import requests
import re

url = 'http://app.lotto.pl/wyniki/?type=dl'
p = re.compile(r'(?<!-)\b\d+\b(?!-)')

response = requests.get(url)
data = p.findall(response.text)
print(data)

关于regex - 如何从 requests.get().text 中排除换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com