我想准确地搜索一个单词并使用python文件处理打印行



我有包含以下内容的文件:

"1 2 3 4 5 5 6  searching new
 1 2 3 4 5 5 6  search"
 1 2 3 4 5 5 6  search and"

法典:

with open('largeFile', 'r') as inF:
 for line in inF:
    if 'search' in line:
    # do_something 

我得到了我只想要的第二行的两行。

您可以使用正则表达式。

使用字边界 (\b) 检查words$检查行尾

>>> line = "abc search"
>>> if re.search('(\b(search)\b)$', line):
          print "true"

true
>>> line1 = "search asdf"
>>> if re.search('(\b(search)\b)$', line):
          print "true"
>>> else:
          print "false"
false

像这样排除searching

with open('largeFile', 'r') as inF:
    for line in inF:
         if not 'searching' in line:
             # do_something 

有点取决于其他线条的外观。更准确地说,您可以执行以下操作:

....if 'search' and not 'searching' in line:

怎么样

if line.endswith("search")

但公平地说,它并不清楚你想要什么。 请发布更多示例行,并告诉我们您期望哪些示例行。

最新更新