簡體   English   中英

我想精確地搜索一個單詞並使用python文件處理來打印行

[英]I wanted to search a word exactly and print line using python file handling

我的檔案包含:

"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 

我得到的兩條線我都只想第二行。

排除這樣的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")

但是公平地說,它並不清楚您想要什么。 請發布更多示例行,並告訴我們您期望哪些行。

您可以使用正則表達式。

使用單詞邊界 (\\ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM