从HTML字符串中删除所有间距
问题描述:
我试图执行删除所有空格和空格字符的代码,然后计算出现在页面中的前3个字母数字字符。我的问题是双重的。从HTML字符串中删除所有间距
1)我用于拆分的方法似乎没有工作,我不知道为什么它不工作。据我所知,加入然后拆分应该从html源代码中删除所有空格和空格,但它不是(请参阅下面的amazon示例中的第一个返回值)。
2)我并不十分熟悉most_common操作,当我测试我的代码的“http://amazon.com”我得到以下输出:
The top 3 occuring alphanumeric characters in the html of http://amazon.com
: [(u' ', 258), (u'a', 126), (u'e', 126)]
什么是ü意味着在返回most_common(3 )值?
我当前的代码:
import requests
import collections
url = raw_input("please eneter the url of the desired website (include http://): ")
response = requests.get(url)
responseString = response.text
print responseString
topThreeAlphaString = " ".join(filter(None, responseString.split()))
lineNumber = 0
for line in topThreeAlphaString:
line = line.strip()
lineNumber += 1
topThreeAlpha = collections.Counter(topThreeAlphaString).most_common(3)
print "The top 3 occuring alphanumeric characters in the html of", url,": ", topThreeAlpha
答
要照顾空白的,你要使用的HTMLParser.HTMLParser及其unescape
方法的实例,以摆脱任何原始的HTML字符躺在附近。要计算字符数,您应该查看collections.Counter。
import requests
from collections import Counter
from HTMLParser import HTMLParser
response = requests.get('http://www.example.com')
responseString = response.text
parser = HTMLParser()
c = Counter(''.join(parser.unescape(responseString).split())
print(c.most_common()[:3])
这意味着它是一个unicode字符串。你用''“'.join(...)''''join'()来加入一个空字符串'”“.join(...) – AChampion