python - 在列表元素中获取子字符串 Python - Web Scraping
问题描述
请原谅我是 Python 和 Selenium 的新手。我正在抓取一个超市网站。我得到的项目名称如下,其中有名称的数量。我想为不同的案例和项目从名称中提取数量,如下所示 -
案例
新鲜价值芋头 250g
新鲜价值香蕉罗布斯塔 1kg
Fresh Value 生木瓜 1 U (units) (300g-400g)
Fresh Value 优质石榴喀布尔 (500g - 700g)
需要的输出:
名称 = Fresh Value Colocasia, 数量 = 250g
名称 = Fresh Value Banana Robusta,数量 = 1kg
名称 - 新鲜价值生木瓜,数量 = 1 U(单位)(300g-400g)
它有数百个这样的项目。我试过使用
str.split()
但没有得到输出。我也尝试过使用正则表达式,但不确定它是如何工作的。有没有一种方法可以在我在字符串中找到一个数字后拆分字符串?任何建议可能会有所帮助。
解决方案
One option (according to the data samples that you provided) can be this:
import re
strings = ['Fresh Value Colocasia 250g', 'Fresh Value Banana Robusta 1kg', 'Fresh Value Raw Papaya 1 U (units) (300g-400g)','Fresh Value Premium Pomegranate Kabul (500g - 700g)']
for i in strings:
start = re.findall('\d|\(', i)[0]
name = i.split(start)[0].strip()
quantity = start + i.split(start)[1]
print 'Name = '+ name + ', Quantity = ', quantity
Output:
Name = Fresh Value Colocasia, Quantity = 250g
Name = Fresh Value Banana Robusta, Quantity = 1kg
Name = Fresh Value Raw Papaya, Quantity = 1 U (units) (300g-400g)
Name = Fresh Value Premium Pomegranate Kabul, Quantity = (500g - 700g)
Of course it is valid if the numbers and parenthesis are present only in the quantity and not in the name. If the quantity starts with other symbols, you can add them in findall
推荐阅读
- garbage-collection - JSON 解码期间的实习字符串是否会提高内存或 GC 压力?
- android-room - 如何将 Android Room 列从 notNull=true 更新为 notNull=false?
- python - 根据值列表从 DataFrame 列中删除值
- java - Checkmarx 报告 sql 注入 JpaRepository
- python - Python 无法导入类,因为找不到它的基本模块
- sql - 如何将 CNAME 别名连接到多个基本可用性组
- reactjs - 强制 React 将更新视为低优先级
- python - Use pandas to combine 2 CSV files
- python - 如何在 Pydantic.schema() 中包含 $id 字段
- python - Python 脚本未执行