python匹配目标词

时间:2016-02-17 18:25:06

标签: python iteration

对于每个目标词,我想检查下一个目标词之前出现的下一个词是否与我在文档中设置的词相对应。如果匹配,我希望它输出为true并写出到txt文件。如果为false,则写出false。

我使用正则表达式,但迭代方式很好

import re
re.findall("([a-zA-Z]+) " + tofind, txt)

目标和下一个词:

target word: document
next words: set is complete

示例文档:

  

我设置的文件现已完成。文件很棒。是   文档很完整,文档集齐全。文件是   完整的文件很好但不完整。

文档在此摘录中出现了6次,但我希望它返回并输出 以下到txt文件

first document -> true
second document -> false
third document -> false
fourth document -> true
fifth document -> false
sixth document -> false

3 个答案:

答案 0 :(得分:1)

不要使用正则表达式来完成此任务,相反,字符串拼接就足够了。一个简单方法的例子:

sampleDoc = "Document that I set is complete now. Document is great set. Is document is great complete document set is complete. Document is complete document is good but not complete.".lower()
findWord = "document".lower()
wordToFind = "set is complete".lower()
splitList = sampleDoc.split(findWord)
splitList.pop(0)
for position,phrase in enumerate(splitList):
    if wordToFind in phrase:
        print("Document Number", str(position+1), "-> true")
    else:
        print("Document Number", str(position+1), "-> false")

我们将文本分成我们想要查找的每个单词,并将其发送到列表中。我们迭代这个列表,如果找到重要的单词,我们输出true,否则输出false。

答案 1 :(得分:0)

使用正则表达式的解决方案,以确保单词边界,单词不是其他单词的一部分(pre set now adays, document 进制):

import re

text='Document that I set is complete now. Document is great set. Is document is great complete document set is complete. Document is complete document is good but not complete.'

target='document'
nextwords='set is complete'

spat = re.compile(r'\b{}\b'.format(re.escape(target)), re.I)
mpat = re.compile(r'\b{}\b'.format(re.escape(nextwords)), re.I)

result = [True if (mpat.search(x)) else False for x in spat.split(text)[1:]]
print(result)

显然,如果targetnextwords以非单词字符开头和结尾,则需要用外观替换单词边界。

答案 2 :(得分:0)

您可以使用documentset is complete属性的所有start&和end的结束索引的星号索引匹配的对象。并通过检查下一个单词的最后一个索引是否在document s的连续对中的一个之间来获得预期的匹配。

>>> all_targets_start = [g.start() for g in re.finditer(r'document', s, re.I)]
>>> all_nextw_end  = [g.end() for g in re.finditer(r'set is complete', s, re.I)]
>>> 
>>> [True if any(i<k<j for k in all_nextw_end) else False for i,j in zip(all_targets_start, all_targets_start[1:])]
[True, False, False, True, False]