【发布时间】:2017-11-03 03:02:01
【问题描述】:
目标是将所有值从百分比转换为小数形式。代码如下:
import requests
from bs4 import BeautifulSoup
import lxml
FIU = open('C://Users//joey//Desktop//response.txt','r').read()
#soup = BeautifulSoup(FIU, "html.parser")
soup = BeautifulSoup(FIU, "lxml")
tables = soup.find_all('table')
for table in tables:
rows = table.find_all("tr")
for row in rows:
cells = row.find_all("td")
if len(cells) == 7: # this filters out rows with 'Term', 'Instructor Name' etc.
for cell in cells:
print(cell.text + "\t", end="") # \t is a Tab character, and end="" prevents a newline between cells
print("") # newline after each row
def p2f(x): return float(x.strip('%'))/100
percentage_list = []
for cell in cells:
if '%' in cell.text:
percentage_list.append(p2f(cell.text))
在最底部,您会看到我尝试去除百分比然后除以 100 以获得每个数字的小数的函数。但是,它并没有影响输出:
Description of course objectives and assignments 0.0% 68.4% 10.5% 15.8% 5.3% 0.0%
Communication of ideas and information 0.0% 52.6% 26.3% 10.5% 10.5% 0.0%
Expression of expectations for performance in this class 0.0% 68.4% 15.8% 10.5% 0.0% 5.3%
Availability to assist students in or out of class 0.0% 57.9% 31.6% 10.5% 0.0% 0.0%
Respect and concern for students 0.0% 47.4% 42.1% 10.5% 0.0% 0.0%
Stimulation of interest in course 0.0% 47.4% 26.3% 21.1% 0.0% 5.3%
Facilitation of learning 0.0% 52.6% 26.3% 10.5% 10.5% 0.0%
Overall assessment of instructor 0.0% 52.6% 31.6% 10.5% 0.0% 5.3%
我可以实现什么代码来解决这个问题?
【问题讨论】:
-
可以打印percentage_list吗?
-
@flamelite 我更新了我的帖子,所以它有输出,如果这就是你的意思?代码本身已经将其“打印”到控制台。
标签: python python-3.x function web-scraping