我想根据单词或句子是否与另一个列表中的条目匹配来对它们进行聚类。
这样:
searchterms = ["windows pc", "linux laptop", "some gibberish"]
osCluster = ["windows", "linux"]
我现在想做的是浏览搜索词并使用osCluster列表对它们进行分类。最后,我想有一个类似csv的格式,如下所示:
- 视窗电脑, 视窗 Linux
- 笔记本电脑,Linux 浏览器
- 一些胡言乱语,不适用
现在我有这样的东西:
for searchterm in searchterms:
for os in osCluster:
if os in searchterm:
print searchterm, os
这导致:
windows pc windows
linux laptop linux
[Finished in 0.0s]
但是,我想将"一些胡言乱语"标记为"N/A"。如果我只是添加:
else:
print searchterm
这将导致:
windows windows
windows
linux
linux linux
gibberish
gibberish
[Finished in 0.0s]
我知道这就是我编写程序要做的事情。但我认为这是错误的思维方式。如果您能用这个为我指出正确的方向,那将非常感激。
你非常接近。 以下是一些修复:
>>> searchterms = ["windows pc", "linux laptop", "some gibberish"]
>>> osCluster = ["windows", "linux"]
>>> for term in searchterms:
found_cluster = 'N/A'
for cluster in osCluster:
if cluster in term:
found_cluster = cluster
break
print('%-15s | %s' % (term, found_cluster))
windows pc | windows
linux laptop | linux
some gibberish | N/A