![](/img/trans.png)
[英]search a word in a file and print the line number where that word occurs in 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.