【发布时间】:2015-12-19 12:11:47
【问题描述】:
我正在尝试过滤已从现有项目列表中搜索到的项目。我当前的代码如下;无论 'last search items.txt' 中的内容是什么,它似乎都不会过滤掉任何项目。
def filter_recent_items(items):
#Clarify item results - only return if it wasn't run in the last search.
#Clears & rewrites items to .txt file after each search
newitems = []
with open('last search items.txt', 'r+') as f:
lines = f.read().split('\n')
print lines
for item in items:
if item['id'] in lines:
pass
else:
newitems.append(item)
f.seek(0)
f.truncate()
for item in items:
f.write("%s \n" % item['id'])
return newitems
函数输入items是一个dict列表(每个item都有一组key):
items = [{'count': 1, 'postage': '0.0', 'listing type': 'StoreInventory', 'title': 'APPLE IPAD AIR 2 WITH RETINA DISPLAY 128GB SPACE GREY UNLOCKED 4G/WIFI', 'price': '828.89', 'start time': '2015-12-19T12:01:19.000Z', 'end time': '2016-01-18T12:06:19.000Z', 'item url': 'http://www.ebay.com.au/itm/APPLE-IPAD-AIR-2-RETINA-DISPLAY-128GB-SPACE-GREY-UNLOCKED-4G-WIFI-/151921257466', 'category': 'iPads, Tablets & eReaders', 'id': '151921257466', 'condition': '3000'},
{'count': 2, 'postage': '13.4', 'listing type': 'FixedPrice', 'title': 'Samsung SM-P350NZAAXSA Galaxy Tab A 8.0 w/S Pen WiFi 16GB NEW', 'price': '340.0', 'start time': '2015-12-19T11:56:51.000Z', 'end time': '2015-12-29T11:56:51.000Z', 'item url': 'http://www.ebay.com.au/itm/Samsung-SM-P350NZAAXSA-Galaxy-Tab-8-0-w-S-Pen-WiFi-16GB-NEW-/252218618062', 'category': 'iPads, Tablets & eReaders', 'id': '252218618062', 'condition': '1000'}]
last search items.txt 将在此函数运行后包含 itemid 列表,例如:
151921257466
252218618062
201487509183
291642436891
272081891024
该函数应打开“last search items.txt”,其中应包含项目 ID 列表(来自先前的搜索)。对于函数输入中的每个项目,它将查看“itemid”是否已经在文本文件中。如果不是,它将项 dict 附加到函数输出。完成此操作后,它会清除文本文件并从“items”中重写项目 ID,为下次调用此函数做好准备。
我的问题是它在文本文件中找不到“itemid”,即使它实际上在其中(不会抛出任何错误消息,只是将“items”的全部内容附加到输出中)。在 Windows 上编辑和测试时工作正常。我已经把它上传到一个 unix VPS 那里它不起作用,稍微编辑它,现在它似乎在 windows 或 unix 上都不起作用!
第二个问题是,有没有更优雅的方法可以过滤项目列表(字典),只返回上次运行脚本时不在列表中的结果?
【问题讨论】:
-
您能否提供 a) 您在错误中得到的具体回溯,以及 b) 在
'last search items.txt'的内容中可能找到的示例。 -
我已经编辑了原帖