找出字串在文本中出现或未出现的情况

【问题】

I’m digging Python sooo much. I love it!

I have come upon my first snag: scanning a file for some strings, and then correctly building separate arrays each of matched, unmatched, and “empty” strings, and then printing each array.

I’ve tried this several ways with several different Python file and sequence iteration constructs (6, I think), with both UTF-8 HTML and ASCII text files.

I have had mixed results - many positive - but none of file.read(), file.readline(), file.readlines(), or file.xreadlines() work as expected after opening the file for reading vai file = open(‘afile’, ‘r’).

:(

I can get part of a given array built, and loop through, but for some reason, a given array is built only partially because the various read*() functions are not working as I have been expecting them to in the script proper….even after testing them successfully in the interpreter!

Code to follow soon, but basically:

tagsf = \[<'tagsfloat1>', '<tagsfloat2>'\]  
tagso = \['<openingtag1>', '<openingtag2>',\]  
tagsc = \['<closingtag1>', '<closingtag2>',\]  
tagp = tagsf + tagso + tagsc  
 
doc = open('afile.html', 'r')  
page = \[\]  
tagy = \[\]  
tagn = \[\]  
for lines in doc.read()  
     page.append(lines)  
 
for line in page:  
    for tag in tagp:  
       if tag in tagy:  
         break  
       if tag in tagn:  
          break  
      if tag in line:  
         if tag not in tagy:  
              tagy.append(tag)  
         if tag not in tagn:  
             tagn.append(tag)  
     
for tagyes in tagy:  
    print tagyes, ' found'  
for tagno in tagn:  
    print tagno ' not found!'  

WTF: All I ever get is the first damn tag found, or all tags NOT found!

【回答】

这个算法应该很简单,将文件读为一个大字符串,然后用关键字列表 tagall 去匹配,获得 tagy,再计算 tagall 和 tagy 的差集,就能获得 tagn。如果不喜欢用循环语句,可以试试 SPL,比 python 写起来更简单易懂,代码如下:


A

1

=[  "tagsfloat1","tagsfloat2","openingtag1","openingtag2"]

2

=file("E:\\afile.html").read()

3

=A1.select(pos(A2,~))

4

=A1\A3


其中 A3 使用了查询函数 select,这表示对 A1 中的成员进行循环访问,如果符合条件,则作为查询结果返回。条件即 A2(大字符串)中是否包含 ~(A1 的当前成员)。

A1\A3 就是求差集。

详细可参考【集算器程序之循环计算】【集算器程序之集合运算符