我有一个日志文件,其中包含输入到网站搜索引擎中的搜索查询.我想将相关的搜索查询“分组”在一起以生成报告.我在大多数Web应用程序中都使用Python-因此该解决方案可以基于Python,或者如果更容易使用sql进行操作,则可以将字符串加载到Postgres中.
示例数据:
dog food
good dog trainer
cat food
veterinarian
组应包括:
猫:
猫食
狗:
dog food
good dog trainer
餐饮:
dog food
cat food
等等…
有想法吗?也许某种“索引算法”?
解决方法:
f = open('data.txt', 'r')
raw = f.readlines()
#generate set of all possible groupings
groups = set()
for lines in raw:
data = lines.strip().split()
for items in data:
groups.add(items)
#parse input into groups
for group in groups:
print "Group \'%s\':" % group
for line in raw:
if line.find(group) is not -1:
print line.strip()
print
#consider storing into a dictionary instead of just printing
可以对它进行重大优化,但是,如果您将原始数据放在外部文本文件中,它将打印以下结果:
Group 'trainer':
good dog trainer
Group 'good':
good dog trainer
Group 'food':
dog food
cat food
Group 'dog':
dog food
good dog trainer
Group 'cat':
cat food
Group 'veterinarian':
veterinarian