python文本解析以获得过滤输出

2024-04-29 18:44:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是寻找文件.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> 

期望的输出是

福特卡车1000.00

我不知道如何进行这项工作。你知道吗


Tags: 项目textdiv名称defaultdatamsgalt
2条回答

使用默认字符串方法查找子字符串索引。例如,"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()

结果在nameprice变量中。如果您想将价格作为一个数字来使用,而不想使用美元符号,请将其添加到strip参数中(.strip("$ "),请阅读Python文档中关于该方法的更多信息)。您可以通过调用price字符串上的replace(",", "")来删除逗号,然后使用float(price)
将字符串转换为浮点值 注意:这可能只是您将解析的字符串放入的方式,但是我添加了strip()rstrip()方法来消除price字符串两端的空白。你知道吗

好吧,请构造更健壮的正则表达式来匹配您的成本和/或品牌,这里有一些代码让您开始。你知道吗

str = '<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>'

import re

brand=re.search('<data-default-alt=\"(.*?)">',str)
cost=re.search('\$(\d+,?\d*\.\d+)</p>',str)
if brand:
        print brand.group(1)
if cost:
        print cost.group(1)

相关问题 更多 >