在较大的字符串中查找较小的字符串

时间:2014-08-04 22:31:41

标签: python string file find

我试图编写一些循环遍历字符串文件(县名)的逻辑,并检查它们是否在另一个文件中的较大字符串中(恶劣天气警告)。我读过的所有内容都告诉我正确地执行此操作但是代码不匹配。任何帮助,将不胜感激。下面是我的骨架代码。

测试县警告过滤的程序

file1 = 'path/to/file1'
file2 = 'path/to/file2'

fp = open(file1,'rb')
string = fp.read()
fp.close()


file = open(file2,'rb')

for line in file:
    if line in string:
        print("found")
    else:
        print("not found")

文件1的示例:

BULLETIN - IMMEDIATE BROADCAST REQUESTED  
SEVERE THUNDERSTORM WARNING  
NATIONAL WEATHER SERVICE JACKSON MS  
457 PM CDT MON AUG 4 2014  

THE NATIONAL WEATHER SERVICE IN JACKSON HAS ISSUED A  

* SEVERE THUNDERSTORM WARNING FOR...  
  EASTERN FRANKLIN COUNTY IN SOUTHWEST MISSISSIPPI...  
  CENTRAL LINCOLN COUNTY IN SOUTH CENTRAL MISSISSIPPI...  

* UNTIL 545 PM CDT  

file2示例:

FRANKLIN COUNTY

LINCOLN COUNTY

Ect...

1 个答案:

答案 0 :(得分:3)

line包含换行符('\n')。

尝试更改

if line in string:

if line.strip() in string: