python-分组相关的搜索关键字

我有一个日志文件,其中包含输入到网站搜索引擎中的搜索查询.我想将相关的搜索查询“分组”在一起以生成报告.我在大多数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

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...