python倒排索引(Inverted index)
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 indicesfor word in mydict.keys():print "%s: %s" % (word,", ".join(map(str,sorted(mydict[word]))))def andSearch(words_list):global mydicta = set(range(1,101))for word in words_list:a = a.intersection(set(mydict[word])) return a def orSearch(words_list):global mydicta = set([])for word in words_list:a = a.union(set(mydict[word]))return a # Queryindex = 100u = 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大致思想就是这样。
。
。
。
。
。
。
。
Python和Perl是什么软件,中文叫什么名字?怎么读?
“Python”这个英文单词的发音似“派森”,因此中文可以称之为派森。
Python是一个有10年历史的Windows编程语言。
Python的创始人为Guido van Rossum。
Python是一种即译式的,互动的,面向对象的编程语言,它包含了模组式的操作,异常处理,动态资料形态,十分高层次的动态资料结构,以及类别的使用。
Python揉合了简单的语法和强大的功能。
它的语法表达优美易读。
它具有很多优秀的脚本语言的特点:解释的,面向对象的,内建的高级数据结构,支持模块和包,支持多种平台,可扩展。
而且它还支持交互式方式运行,图形方式运行。
它拥有众多的编程界面支持各种操作系统平台以及众多的各类函数库。
利用C和C++可以对它进行扩充。
个别的应用软件如果需要有一个可程序化界面也可以利用它来做为扩展语言用。
最后,Python的可移植度非常高:它可以在许多的Unix类平台上运行,在Mac,MS-DOS,视窗Windows,Windows NT,OS/2,BeOS,以至RISCOS上都有相关的Python版本。
Perl是Practical Extraction and Report Language的缩写,它是由Larry Wall设计的,并由他不断更新和维护,用于在UNIX环境下编程。
没有中文名。
教程:http://doc.99net.net/doc/program/1076664628/1076664648.html
如何对excel表格里的词结巴分词python
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257 # -*- coding: utf-8 -*- importjieba ''''' Created on 2015-11-23 '''defword_split(text): """ Split a text in words. Returns a list of tuple that contains (word, location) location is the starting byte position of the word. """ word_list =[] windex =0 word_primitive =jieba.cut(text, cut_all =True) forword inword_primitive: iflen(word) > 0: word_list.append((windex, word)) windex +=1 returnword_list definverted_index(text): """ Create an Inverted-Index of the specified text document. {word:[locations]} """ inverted ={} forindex, word inword_split(text): locations =inverted.setdefault(word, []) locations.append(index) returninverted definverted_index_add(inverted, doc_id, doc_index): """ Add Invertd-Index doc_index of the document doc_id to the Multi-Document Inverted-Index (inverted), using doc_id as document identifier. {word:{doc_id:[locations]}} """ forword, locations indoc_index.iteritems(): indices =inverted.setdefault(word, {}) indices[doc_id] =locations returninverted defsearch_a_word(inverted, word): """ search one word """ word =word.decode('utf-8') ifword notininverted: returnNone else: word_index =inverted[word] returnword_index defsearch_words(inverted, wordList): """ search more than one word """ wordDic =[] docRight =[] forword inwordList: ifisinstance(word,str): word =word.decode('utf-8') ifword notininverted: returnNone else: element =inverted[word].keys() element.sort() wordDic.append(element) numbers =len(wordDic) inerIndex =[0fori inrange(numbers)] docIndex =[wordDic[i][0] fori inrange(numbers)] flag =True whileflag: ifmin(docIndex) ==max(docIndex): docRight.append(min(docIndex)) inerIndex =[inerIndex[i]+1fori inrange(numbers)] fori inrange(numbers): ifinerIndex[i] >=len(wordDic[i]): flag =False returndocRight docIndex =[wordDic[i][inerIndex[i]] fori inrange(numbers)] else: minIndex =min(docIndex) minPosition =docIndex.index(minIndex) inerIndex[minPosition] +=1 ifinerIndex[minPosition] >=len(wordDic[minPosition]): flag =False returndocRight docIndex =[wordDic[i][inerIndex[i]] fori inrange(numbers)] defsearch_phrase(inverted, phrase): """ search phrase """ docRight ={} temp =word_split(phrase) wordList =[temp[i][1] fori inrange(len(temp))] docPossible =search_words(inverted, wordList) fordoc indocPossible: wordIndex =[] indexRight =[] forword inwordList: wordIndex.append(inverted[word][doc]) numbers =len(wordList) inerIndex =[0fori inrange(numbers)] words =[wordIndex[i][0] fori inrange(numbers)] flag =True whileflag: ifwords[-1] -words[0] ==numbers -1: indexRight.append(words[0]) inerIndex =[inerIndex[i]+1fori inrange(numbers)] fori inrange(numbers): ifinerIndex[i] >=len(wordIndex[i]): flag =False docRight[doc] =indexRight break ifflag: words =[wordIndex[i][inerIndex[i]] fori inrange(numbers)] else: minIndex =min(words) minPosition =words.index(minIndex) inerIndex[minPosition] +=1 ifinerIndex[minPosition] >=len(wordIndex[minPosition]): flag =False break ifflag: words =[wordIndex[i][inerIndex[i]] fori inrange(numbers)] returndocRight if__name__ =='__main__': doc1 =""" 中文分词指的是将一个汉字序列切分成一个一个单独的词。
分词就是将连续的字序列按照一定的规范 重新组合成词序列的过程。
我们知道,在英文的行文中,单词之间是以空格作为自然分界符的,而中文 只是字、句和段能通过明显的分界符来简单划界,唯独词没有一个形式上的分界符,虽然英文也同样 存在短语的划分问题,不过在词这一层上,中文比之英文要复杂的多、困难的多。
""" doc2 =""" 存在中文分词技术,是由于中文在基本文法上有其特殊性,具体表现在:与英文为代表的拉丁语系语言相比,英文以空格作为天然的分隔符,而中文由于继承自古代汉语的传统,词语之间没有分隔。
古代汉语中除了连绵词和人名地名等,词通...
python 正则表达式 groups和group有什么区别
group和groups是两个不同的函数。
一般,m.group(N) 返回第N组括号匹配的字符。
而m.group() == m.group(0) == 所有匹配的字符,与括号无关,这个是API规定的。
m.groups() 返回所有括号匹配的字符,以tuple格式。
m.groups() == (m.group(0), m.group(1), ...)正则表达式中,group()用来提取分组截获的字符串,()用来分组。
组是通过 "(" 和 ")" 元字符来标识的。
"(" 和 ")" 有很多在数学表达式中相同的意思;它们一起把在它们里面的表达式组成一组。
举个例子,你可以用重复限制符,象 *, +, ?, 和 {m,n},来重复组里的内容,比如说(ab)* 将匹配零或更多个重复的 "ab"。
如果不引入括号,整个个表达式作为一个组,是group(0)对于题目中的例子:m = re.match("([abc])+", "abc")+号在括号外面。
括号最多匹配到一个字符,要么是a, 要么是c,这个python引擎匹配的是末尾的c。
而m.group() == m.group(0) 这个返回的是整个匹配的字符串"abc".
python中怎么返回指定查找字符的位置
Python编程中对字符串进行搜索查找,并返回字符位置,案例代码如下:# multiple searches of a string for a substring # using s.find(sub[ ,start[, end]]) #以下面test这段文本为例text = 'MSKSASPKEPEQLRKLFIGGLSFETTDESLRSAHFESSSYGSAGRRF' ##查找上面文本中的SA字符串 search = 'SA' start = 0 while True: index = text.find(search, start) # if search string not found, find() returns -1 # search is complete, break out of the while loop if index == -1: break print( "%s found at index %d" % (search, index) ) # move to next possible start position start = index + 1 //运行结果:#SA found at index 3#SA found at index 31#SA found at index 41
python 命名组的问题:这个?P怎么和1是一个意思的?其实它...
?P是给正则中的组起一个名字group(1)-group(9)是按正则中左括号的顺序确定组的顺序,因此正则中第一对括号匹配的内容就是group(1)(?P....) 无论它出现在第几个括号中,都是这个名字,与圆括号的顺序无关,它出现在的那对括号内,就表示这个括号内匹配的内容就是group(name)
如何对excel表格里的词结巴分词python
展开全部# -*- coding: utf-8 -*- import jieba ''''' Created on 2015-11-23 ''' def word_split(text): """ Split a text in words. Returns a list of tuple that contains (word, location) location is the starting byte position of the word. """ word_list = [] windex = 0 word_primitive = jieba.cut(text, cut_all = True) for word in word_primitive: if len(word) > 0: word_list.append((windex, word)) windex += 1 return word_list def inverted_index(text): """ Create an Inverted-Index of the specified text document. {word:[locations]} """ inverted = {} for index, word in word_split(text): locations = inverted.setdefault(word, []) locations.append(index) return inverted def inverted_index_add(inverted, doc_id, doc_index): """ Add Invertd-Index doc_index of the document doc_id to the Multi-Document Inverted-Index (inverted), using doc_id as document identifier. {word:{doc_id:[locations]}} """ for word, locations in doc_index.iteritems(): indices = inverted.setdefault(word, {}) indices[doc_id] = locations return inverted def search_a_word(inverted, word): """ search one word """ word = word.decode('utf-8') if word not in inverted: return None else: word_index = inverted[word] return word_index def search_words(inverted, wordList): """ search more than one word """ wordDic = [] docRight = [] for word in wordList: if isinstance(word, str): word = word.decode('utf-8') if word not in inverted: return None else: element = inverted[word].keys() element.sort() wordDic.append(element) numbers = len(wordDic) inerIndex = [0 for i in range(numbers)] docIndex = [wordDic[i][0] for i in range(numbers)] flag = True while flag: if min(docIndex) == max(docIndex): docRight.append(min(docIndex)) inerIndex = [inerIndex[i]+1 for i in range(numbers)] for i in range(numbers): if inerIndex[i] >= len(wordDic[i]): flag = False return docRight docIndex = [wordDic[i][inerIndex[i]] for i in range(numbers)] else: minIndex = min(docIndex) minPosition = docIndex.index(minIndex) inerIndex[minPosition] += 1 if inerIndex[minPosition] >= len(wordDic[minPosition]): flag = False return docRight docIndex = [wordDic[i][inerIndex[i]] for i in range(numbers)] def search_phrase(inverted, phrase): """ search phrase """ docRight = {} temp = word_split(phrase) wordList = [temp[i][1] for i in range(len(temp))] docPossible = search_words(inverted, wordList) for doc in docPossible: wordIndex = [] indexRight = [] for word in wordList: wordIndex.append(inverted[word][doc]) numbers = len(wordList) inerIndex = [0 for i in range(numbers)] words = [wordIndex[i][0] for i in range(numbers)] flag = True while flag: if words[-1] - words[0] == numbers - 1: indexRight.append(words[0]) inerIndex = [inerIndex[i]+1 for i in range(numbers)] for i in range(numbers): if inerIndex[i] >= len(wordIndex[i]): flag = False docRight[doc] = indexRight break if flag: words = [wordIndex[i][inerIndex[i]] for i in range(numbers)] else: minIndex = min(words) minPosition = words.index(minIndex) inerIndex[minPosition] += 1 if inerIndex[minPosition] >= len(wordIndex[minPosition]): flag = False break if flag: words = [wordIndex[i][inerIndex[i]] for i in range(numbers)] return docRight if __name__ == '__main__': doc1 = """ 中文分词指的是将一个汉字序列切分成一个一个单独的词。
分词就是将连续的字序列按照一定的规范 重新组合成词序列的过程。
我们知道,在英文的行文中,单词之间是以空格作为自然分界符的,而中文 只是字、句和段能通过明显的分界符来简单划界,唯独词没有一个形式上的分界符,虽然英文也同样 存在短语的划分问题,不过在词这一层上,中文比之英文要复杂的多、困难的多。
""" doc2 = """ 存在中文分词技术,是由于中文在基本文法上有其特殊性,具体表现在: 与英文为代表的拉丁语系语言相比,英文以空格作为天然的分隔符,而中文由于继承自古代汉语的传统, 词语之间没有分隔。
古代汉语中除了连绵词和人名地名等,词通常就是单个汉字,所以当时没有分词 书写的必要。
而现代汉语中双字或多字词居多,一个字不再等同于一个词。
在中文里,“词”和“词组”边界模糊 现代汉语的基本表达单元虽然为“词”,且以双字或者多字词居多,但由于人们认识水平的不同,对词和 短语的边界很难去区分。
例如:“对随地吐痰者给予处罚”,“随地吐痰者”本身是一个词还是一个短语,不同的人会有不同的标准, 同样的“海上”“酒厂”等等,即使是同一个人也可能做出不同判断,如果汉语真的要分词书写,必然会出现 混乱,难度很大。
中文分词的方法其实不局限于中文应用,也被应用到英文处理,如手写识别,单词之间的空格就不很清楚, 中文分词方法可以帮助判别英文单词的边界。
""" doc3 = """ 作用 中文分词是文本挖掘的基础...
python 中的问题 关于re模块
jieba"结巴"中文分词:做最好的Python中文分词组件"Jieba"(Chinesefor"tostutter")Chinesetextsegmentation:builttobethebestPythonChinesewordsegmentationmodule.ScrolldownforEnglishdocumentation.Feature支持三种分词模式:精确模式,试图将句子最精确地切开,适合文本分析;全模式,把句子中所有的可以成词的词语都扫描出来,速度非常快,但是不能解决歧义;搜索引擎模式,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词。
支持繁体分词支持自定义词典在线演示/huaban/jieba-analysisAlgorithm基于Trie树结构实现高效的词图扫描,生成句子中汉字所有可能成词情况所构成的有向无环图(DAG)采用了动态规划查找最大概率路径,找出基于词频的最大切分组合对于未登录词,采用了基于汉字成词能力的HMM模型,使用了Viterbi算法功能1):分词jieba.cut方法接受两个输入参数:1)第一个参数为需要分词的字符串2)cut_all参数用来控制是否采用全模式jieba.cut_for_search方法接受一个参数:需要分词的字符串,该方法适合用于搜索引擎构建倒排索引的分词,粒度比较细注意:待分词的字符串可以是gbk字符串、utf-8字符串或者unicodejieba.cut以及jieba.cut_for_search返回的结构都是一个可迭代的generator,可以使用for循环来获得分词后得到的每一个词语(unicode),也可以用list(jieba.cut())转化为list代码示例(分词)#encoding=utf-8importjiebaseg_list=jieba.cut("我来到北京清华大学",cut_all=True)print"FullMode:","/".join(seg_list)#全模式seg_list=jieba.cut("我来到北京清华大学",cut_all=False)print"DefaultMode:","/".join(seg_list)#精确模式seg_list=jieba.cut("他来到了网易杭研大厦")#默认是精确模式print",".join(seg_list)seg_list=jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造")#搜索引擎模式print",".join(seg_list)Output:【全模式】:我/来到/北京/清华/清华大学/华大/大学【精确模式】:我/来到/北京/清华大学【新词识别】:他,来到,了,网易,杭研,大厦(此处,“杭研”并没有在词典中,但是也被Viterbi算法识别出来了)【搜索引擎模式】:小明,硕士,毕业,于,中国,科学,学院,科学院,中国科学院,计算,计算所,后,在,日本,京都,大学,日本京都大学,深造功能2):添加自定义词典开发者可以指定自己自定义的词典,以便包含jieba词库里没有的词。
虽然jieba有新词识别能力,但是自行添加新词可以保证更高的正确率用法:jieba.load_userdict(file_name)#file_name为自定义词典的路径词典格式和dict.txt一样,一个词占一行;每一行分三部分,一部分为词语,另一部分为词频,最后为词性(可省略),用空格隔开范例:之前:李小福/是/创新//主任/也/是/云/计算/方面/的/专家/加载自定义词库后: 李小福/是/创新/主任/也/是/云计算/方面/的/专家/自定义词典:/fxsjy/jieba/blob/master/test/test_userdict.py"通过用户自定义词典来增强歧义纠错能力"---/fxsjy/jieba/blob/master/test/extract_tags.py功能4):词性标注标注句子分词后每个词的词性,采用和ictclas兼容的标记法用法示例>>>importjieba.possegaspseg>>>words=pseg.cut("我爱北京天安门")>>>forwinwords:printw.word,w.flag我r爱v北京ns天安门ns功能5):并行分词原理:将目标文本按行分隔后,把各行文本分配到多个python进程并行分词,然后归并结果,从而获得分词速度的可观提升基于python自带的multiprocessing模块,目前暂不支持windows用法:jieba.enable_parallel(4)#开启并行分词模式,参数为并行进程数jieba.disable_parallel()#关闭并行分词模式例子:/fxsjy/jieba/blob/master/test/parallel/test_file.py实验结果:在4核3.4GHzLinux机器上,对金庸全集进行精确分词,获得了1MB/s的速度,是单进程版的3.3倍。
功能6):Tokenize:返回词语在原文的起始位置注意,输入参数只接受unicode默认模式result=jieba.tokenize(u'永和服装饰品有限公司')fortkinresult:print"word%s\t\tstart:%d\t\tend:%d"%(tk[0],tk[1],tk[2])word永和start:0end:2word服装start:2end:4word饰品start:4end:6word有限公司start:6end:10搜索模式result=jieba.tokenize(u'永和服装饰品有限公司',mode='search')fortkinresult:print"word%s\t\tstart:%d\t\tend:%d"%(tk[0],tk[1],tk[2])word永和start:0end:2word服装start:2end:4word饰品start:4end:6word有限start:6end:8word公司start:8end:10word有限公司start:6end:10功能7):ChineseAnalyzerforWhoosh搜索引擎引用:fromjieba.analyseimportChineseAnalyzer用法示例:/fxsjy/jieba/raw/master/extra_dict/dict.txt.big下载你所需要的词典,然后覆盖jieba/dict.txt即可或者用jieba.set_dictionary('data/dict.txt.big')模块初始化机制的改变:lazyload(从0.28版本开始)jieba采用延迟加载,"importjieba"不会立即触发词典的加载,一旦有必要才开始加载词典构建trie。
如果你想手工初始jieba,也可以手动初始化。
importjiebajieba.initialize()#手动初始化(可选)在0.28之前的版本是不能指定主词...
转载请注明出处51数据库 » wordsearch Python