使用 re.sub 过滤来自 urllib 的 html 响应

Filter html response from urllib with re.sub

我想做的是获取网站的 html 响应作为可变字符串,并过滤掉除点 (.)、数字 (0-9)、冒号 (:) 之外的所有内容。我似乎无法用 re.sub 来解决这个问题。可能吗 ?

import urllib.request
import re

ans = True

while ans:
    print("""
      - Menu Selection -
      1. Automatic 
      2. Automatic w/Checker
      3. Manual
      4. Add to list
      5. Exit
      """)
ans = input('Select Option : ')

 if ans =="1":
    try :
        with urllib.request.urlopen('http://www.mywebsite.net') as response: 
           html = response.read()
           html = str(html)
           html = re.sub(r'([a-z][A-Z])', '', html)
           f = open('text.txt','a')
           f.write(html)
           f.close()
           print('Data(1) saved.')
           ans = True
    except :
            print('Error on first fetch.')    

这会输出整个 html 代码并且不会过滤掉任何字符。 感谢任何帮助:)

我们想要html = re.sub('[0-9.:]', '', html)。 Python 中的字符串是不可变的,因此修改字符串的唯一方法是构造一个新字符串:因此所有字符串函数 returns 新字符串而不是就地修改它们(这在 Python).这个新字符串必须分配给某个变量,否则它将永远丢失(如您的示例所示)。

你必须排除你提到的三件事并制作如下模式 - 这里 html 是你的输入字符串

re.sub('[^0-9\.:]', '', html)