python倒排索引(Inverted index)

Python0151

python倒排索引(Inverted index),第1张

s = raw_input()

lines = s.split('\n')

dictlines = lines[:100]

mydict = {}

# read 

for i,line in enumerate(dictlines ):

    for word in line.split():

      mydict.setdefault(word,[]).append(i + 1)

# print indices

for word in mydict.keys():

    print "%s: %s"  % (word,", ".join(map(str,sorted(mydict[word]))))

 

def andSearch(words_list):

    global mydict

    a = set(range(1,101))

    for word in words_list:

        a = a.intersection(set(mydict[word])) 

     return a 

def orSearch(words_list):

    global mydict

    a = set([])

    for word in words_list:

        a = a.union(set(mydict[word]))

    return a 

    

# Query

index = 100

u = lines[index]

while index < len(lines):

    words_list = u.split()

    if ":" in u:

        if words_list[0] == "OR:":

            a = orSearch(words_list)

        else:

            if words_list[0] == 'AND:':

               words_list = words_list[1:]

            a = andSearch(words_list)

    if not a:

        print ", ".join(map(str,list(a)))

    else:

        print "None"

    index += 1

大致思想就是这样。。。。。。。。

倒置字符串 将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I

解题思路:

先将字符串整体逆置,然后再逆置以空格分隔的单词,这样就可以达到我们想要的效果。

例如:

输入:I like beijing.

输出:beijing. like I

因为Python默认是以ASCII作为编码方式的,如果在自己的Python源码中(即使是注释部分)包含了中文(或者其他非英语系的语言),此时即使你把自己编写的Python源文件以UTF-8格式保存了,但实际上,这依然是不行的。

解决方法:源代码文件第一行添加:#coding:utf-8,这样就可以避免了,也可以改为,在第一行增加:#-- coding: UTF-8 --

编写程序以字符串为单位,以空格或标点符号(字符串中仅含英文逗号','或小数点'.'作为标点符号)作为分隔符,对字符串中所有单词进行倒排,然后把已处理的字符串(应不含标点符号)打印出来。

Python语言是一款对缩进非常敏感的语言,给很多初学者带来了困惑,即便是很有经验的Python程序员,也可能陷入陷阱当中。最常见的情况是tab和空格的混用会导致错误,或者缩进不对,而这是用肉眼无法分别的。

在编译时会出现这样的错IndentationError:expected an indented block说明此处需要缩进,你只要在出现错误的那一行,按空格或Tab(但不能混用)键缩进就行。

往往有的人会疑问:我根本就没缩进怎么还是错,不对,该缩进的地方就要缩进,不缩进反而会出错。