我的目标是搜索file.txt以查找标识字符串,然后在引号之间输出以下单词。
因此标识符将是data-default-alt =并且项目的名称是" Ford Truck"在引号中。我想输出项目的名称和价格,以便我可以在Excel中打开它。
data-default-alt="Ford Truck"> </h3> </a> </div> <div class="tileInfo"> <div class="swatchesBox--empty"></div> <div class="promo-msg-text"> <span class="calloutMsg-promo-msg-text"></span> </div> <div class="pricecontainer" data-pricetype="Stand Alone"> <p id="price_206019013" class="price price-label "> $1,000.00 </p>
所需的输出将是
Ford Truck 1000.00
我不确定如何完成这项任务。
答案 0 :(得分:1)
那么请构建更强大的正则表达式以匹配您的成本和/或品牌,这里有一些代码可以帮助您入门。
DECLARE @tableName varchar(10)
SET @tableName = 'yourtablenamehere'
DECLARE @sql VARCHAR(MAX)
SET @sql = ''
SELECT @sql = @sql + 'UPDATE ' + @tableName + ' SET ' + c.name + ' = '''' WHERE ' + c.name + ' IS NULL ;'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE t.name = @tableName
and c.name regexp `'Q%[0-9]$'`
EXEC (@sql)
答案 1 :(得分:0)
使用默认字符串方法查找子字符串索引。例如,"abcdef".find("bc")
将返回1,这是子字符串的第一个字母的索引。要解析字符串,您可以查找标签,然后使用字符串切片提取所需的文本
所以这是解决问题的一个例子,考虑到解析后的字符串存储在st
变量中:
with open("file.txt") as f:
st = f.read() # that's to get the file contents
name_start = st.find('data-default-alt="') + len('data-default-alt="') # found the first letter's index and added the substring's length to it to skip to the part of the actual data
name_end = st[name_start:].find('"') # found the closing quote
name = st[name_start:name_start + name_end] # sliced the string to get what we wanted
price_start = st.find('class="price price-label ">') + len('class="price price-label ">')
price_end = st[price_start:].find('</p>')
price = st[price_start:price_start + price_end].strip().rstrip()
结果位于name
和price
个变量中。如果您想将价格作为数字而不想要美元符号,请将其添加到条带参数(.strip("$ ")
,在Python文档中阅读有关该方法的更多信息)。您可以通过调用价格字符串上的replace(",", "")
删除逗号,然后使用float(price)
将字符串转换为浮点数
注意:它可能就是您将解析后的字符串放入的方式,但我已经添加了strip()
和rstrip()
方法来消除价格字符串每一端的空格。