Python:从字符串中提取文本
我有两张单子Python:从字符串中提取文本,python,Python,我有两张单子 tvmodels.txt vendors.txt 在这些列表中,所有电视型号和电视供应商都在其中 文件的输入如下所示: tvmodels.txt file KDL40W705CBAEP KDL55W755CBAEP KD75XD8505BAEP KDL40WD650BAEP UE75H6470AWXXN vendors.txt file SAMSUNG SONY LG PHILIPS PANASONIC 当我使用脚本时,mshtv['item_2_name']返回SAMSU
- tvmodels.txt
- vendors.txt
tvmodels.txt file
KDL40W705CBAEP
KDL55W755CBAEP
KD75XD8505BAEP
KDL40WD650BAEP
UE75H6470AWXXN
vendors.txt file
SAMSUNG
SONY
LG
PHILIPS
PANASONIC
当我使用脚本时,mshtv['item_2_name']返回SAMSUNGUE75H6470LEDTV(平板、75Zoll、全高清、3D、智能电视)
现在我想要实现的是:
1) 我从mshtv['item\u vendor']
字段中的vendors.txt
文件中获取任何供应商。在本例中,这将是SAMSUNG
2) 我从tvmodels.txt
文件中获取任何电视模型,该文件位于mshtv['item\u model']
字段中。在本例中,这将是UE75H6470
对于电视模特来说,还有一个陷阱。在tvmodels.txt
文件中,所有电视型号均采用官方供应商格式。对于本例,它在列表中的名称为UE75H6470AWXXN
。
其背后的原因是,一些零售商正在使用完整的电视模型参考,而另一些则只是部分使用
如果尝试使用(如果有的话)
,但不起作用。我环顾四周,但找不到任何其他解决方案。有什么建议吗
import scrapy.selector
import urlparse
from scrapy.spiders import Spider
from scrapy.http import Request
from MediaMarkt.items import MediamarktItem
models = []
for line in open("tvmodels.txt", "r"):
models.append(line.strip("\n\-"))
d = {}
for model in models:
d[model] = True
vendors = []
for line in open("vendors.txt", "r"):
vendors.append(line.strip("\n\-"))
e = {}
for vendor in vendors:
e[vendor] = True
def complete_url(string):
return "http://www.mediamarkt.de"+ string
def encode(str):
return str.encode('utf8', 'ignore')
class MshbeSpider(Spider):
name = "mshdetv"
start_urls = ['http://www.mediamarkt.de/mcs/productlist/_led-lcd-fernseher,48353,460668.html?langId=-3&searchParams=&sort=&view=&page=']
def parse(self, response):
items = response.xpath('//ul[@class="products-list"]/li/div')
for item in items:
mshtv = MediamarktItem()
mshtv['item_3_price'] = encode(item.xpath('normalize-space(.//aside/div/div/div/text())').extract()[0]).replace("-","")
mshtv['item_2_name'] = encode(item.xpath('normalize-space(.//div/h2/a/text())').extract()[0]).replace("-","").replace(" C","C").replace(" B","B").replace(" ","")
mshtv['item_a_link'] = item.select('.//div/h2/a/@href').extract()
mshtv['item_4_avai'] = encode(item.xpath('normalize-space(.//aside/div/div/ul/li//text())').extract()[0])
#mshtv['item_1_cat'] = encode(item.xpath('normalize-space(//*[@id="category"]/hgroup/h1/text())').extract()[0])
for word in mshtv['item_2_name'].split(" "):
if word in d:
mshtv['item_model'] = word
for word in mshtv['item_2_name'].split(" "):
if word in e:
mshtv['item_vendor'] = word
yield mshtv
new_link = response.xpath('//li[@class="pagination-next"]/a/@href').extract()[0]
yield Request(complete_url(new_link),callback=self.parse)
如果您将问题编辑为包含输入文件中的一些样本行,则会有所帮助。如果您将问题编辑为包含输入文件中的一些样本行,则会有所帮助。