[英]Remove unwanted characters from string with BeautifulSoup Python when selecting words from string
[英]Cannot clean string from unwanted characters using Python beautifulsoup
当我运行以下
prices = [price.text.strip() for price in soup.select('.special-price')]
prices = prices.replace(u'\xa0', u' ')
print(prices)
我得到“列表”对象没有属性“替换”
我应该放在哪里替换? 有什么方法可以一步一步清除它吗?
谢谢
由于我们无权访问您的示例数据,因此应该这样做:
您需要将replace()
放在str
而不是list
,例如:
prices = ['1','1','2','3','4','5','1','1','1']
print([x.replace('1', '9') for x in prices])
输出 :
['9', '9', '2', '3', '4', '5', '9', '9', '9']
是的,因为您使用列表理解功能创建了一个列表
您需要通过prices=''.join(prices)
将列表转换为字符串,前提是如果价格未解析为字符串,则为字符串列表。 价格将是一个字符串。 现在您可以调用replace了。
因为'list' object has no attribute 'replace'
。 这就是为什么。
您正在尝试单独更改价格。 字符串具有replace
方法,但列表没有。
您应该将replace添加到列表理解中。
prices = [price.text.strip().replace(u'\xa0', u' ') for price in soup.select('.special-price')]
print(prices)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.