python - 如何从 python 的列表中删除某些元素?
问题描述
我正在从网站上抓取一些数据,但其中一些数据前面带有“\”。我尝试使用此代码字符串,但出现错误消息。
print([s.strip('\') for s in feet]) *EOL while scanning string literal
print([s.replace('\', ') for s in feet])
第一行中'\'之后的代码变成了斜体,我不知道该怎么做。
from lxml import html
import requests
list1 = []
height = []
user_website = "https://www.disabled-world.com/calculators-charts/height-weight.php"
page = requests.get(user_website)
tree = html.fromstring(page.content)
list2 = tree.xpath('//td/text()')
for x in list2:
list_holder = x.split(" ")
for i in list_holder:
list1.append(i.lower())
subs = "'"
feet = [i for i in list2 if subs in i]
subs2 = '"'
inches = [i for i in list2 if subs in i]
print([s.strip('\') for s in feet])
print([s.replace('\', ') for s in feet])
y = 0
for x in feet:
height.append(feet[y])
height.append(inches[y])
y+=1
print(height)
解决方案
所以我试图提取你的代码,这是:
from lxml import html
import requests
list1 = []
height = []
user_website = "https://disabled-world.com/calculators-charts/height-weight.php"
page = requests.get(user_website)
tree = html.fromstring(page.content)
list2 = tree.xpath('//td/text()')
for x in list2:
list_holder = x.split(" ")
for i in list_holder:
list1.append(i.lower())
subs = "'"
feet = [i for i in list2 if subs in i]
subs2 = '"'
inches = [i for i in list2 if subs in i]
print([s.strip('"') for s in feet])
#print([s.replace('\', ') for s in feet])
y = 0
#for x in feet:
# height.append(feet[y])
# height.append(inches[y])
# y+=1
# print(height)
给我以下输出:
["4' 6", "4' 7", "4' 8", "4' 9", "4' 10", "4' 11", "5' 0", "5' 1", "5' 2", "5' 3", "5' 4", "5' 5", "5' 6", "5' 7", "5' 8", "5' 9", "5' 10", "5' 11", "6' 0", "6' 1", "6' 2", "6' 3", "6' 4", "6' 5", "6' 6", "6' 7", "6' 8", "6' 9", "6' 10", "6' 11", "7' 0"]
根据您的问题,我认为这就是您想要的?
无论如何,问题(据我所知)只是strip()
函数的错误使用,它需要一个字符串(包含您要剥离的源字符串的一部分),而不仅仅是一个字符。
推荐阅读
- javascript - 如何使用 fetch() 将 html 表单数组传递给 PHP?
- r - 随机因素给我在 R 中运行统计模型带来了麻烦
- mongodb - MongoDB - 从多个子目录更新一个字段值
- vue.js - Vue.js + .netcore MPA
- python - 在 groupby 之后过滤具有最大行值的列组合
- python - 如何在 Sikuli 中发送“Ctrl + Shift + t”?
- ant - 仅当 Apache ant 中存在相应文件时,如何复制文件?
- php - 为什么即使我检查等于 PHP 条件也会变为真
- sql - SQL选择最年轻的记录
- javascript - vue组件之间如何传递数据