Python 3特殊字符转义 [英] Python 3 Special characters escaping
本文介绍了Python 3特殊字符转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从urllib.request导入urllib
导入urlopen
address ='http://www.iitb.ac.in /acadpublic/RunningCourses.jsp?deptcd=EE&year=2012&semester=1'
source = urlopen(address).read()
source = str(source)
$ b $来自html.parser的b
导入HTMLParser
类MyHTMLParser(HTMLParser):
def handle_data(self,data):
x = str(data)
如果x!=('\\\\\\\\\\\'')或('\\\\\\\\\\\\\ ')或('\\\\\\\\\\\''):
print(遇到一些数据:,x)
parser = MyHTMLParser(strict = False)
parser.feed(source)
上面的代码不起作用。它仍在打印'\\\\\\\\\\\''的东西。有什么建议吗?
解决方案
if x!=('\\\\\ \\ t \\\\\'或)('\\\\\\\\\\\\'或'''\\\\ r\\\
\t\t\t')
应该是
如果x不在('\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\ code>或更好:
如果不是x.isspace()
您的第一个代码被评估为:
if(x!=('\\\\\\\\\\\')'或'\ r \ n \\\\\\\\'或'\\\\\\\\\\\\'$'
注意最后的值是自己评估的!只有一个空字符串将评估 False
因此这个条件将始终传递
import urllib
from urllib.request import urlopen
address='http://www.iitb.ac.in/acadpublic/RunningCourses.jsp?deptcd=EE&year=2012&semester=1'
source= urlopen(address).read()
source=str(source)
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_data(self, data):
x=str(data)
if x != ('\r\n\t\t\t\t') or ('\r\n\t\t\t\t\t') or ('\r\n\r\n\t\t\t'):
print("Encountered some data:",x)
parser = MyHTMLParser(strict=False)
parser.feed(source)
The above code isn't working. It is still printing '\r\n\t\t\t\t' stuff. Any suggestions?
解决方案
if x != ('\r\n\t\t\t\t') or ('\r\n\t\t\t\t\t') or ('\r\n\r\n\t\t\t')
should be
if x not in ('\r\n\t\t\t\t', '\r\n\t\t\t\t\t', '\r\n\r\n\t\t\t')
or better:
if not x.isspace()
Your first code is evaluated as:
if (x != ('\r\n\t\t\t\t')) or '\r\n\t\t\t\t\t' or '\r\n\r\n\t\t\t'
Notice the last values are evaluated as themselves! Only an empty string will evaluate False
thus this condition will always pass
这篇关于Python 3特殊字符转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文