0

コードが US-NJ-Camden のようになるようにデータを連結するにはどうすればよいですか。

def parse_items(self, response):
     hxs = HtmlXPathSelector(response)
     loc_Con = hxs.select('/tr/td[2]/span/span/span') #for country
     loc_Reg = hxs.select('/tr/td[2]/span/span') #for region
     loc_Loc = hxs.select('//tr[3]/td[2]/span/span') #for local
     items = []
     for titles in titles:
     item = somethingItem()
     item ["country"] = loc_Con.select('text()').extract()
     item ["region"] = loc_Reg.select('text()').extract()
     item ["location"] = loc_Loc.select('text()').extract()
     item ["code"] = #["country"]-item ["region"]-item ["location"] like the above example
4

1 に答える 1

0

次のように使用format()します。

item["code"] = "{}-{}-{}".format(item["country"], item["region"], item["location"])

またはこの方法:

item["code"] = "{country}-{region}-{location}".format(country=item["country"], 
                                                      region=item["region"],
                                                      location=item["location"])

または古いスタイルの書式設定:

item["code"] = "%s-%s-%s" % (item["country"], item["region"], item["location"])

更新:

そして、抽出されたリストから 0 番目の項目を取得することを忘れないでください。

item ["country"] = loc_Con.select('text()').extract()
item ["region"] = loc_Reg.select('text()').extract()
item ["location"] = loc_Loc.select('text()').extract()

item ["country"] = item ["country"][0] if item ["country"] else ""
item ["region"] = item ["region"][0] if item ["region"] else ""
item ["location"] = item ["location"][0] if item ["location"] else ""
于 2013-08-28T07:25:49.170 に答える