[英]How to return lines that have a specific word only
運行一個接受兩個輸入,一個輸入文件和一個要搜索的單詞的簡單程序。 然后,應打印出包含該單詞的所有行。 例如,我的輸入文件包含5個句子,如下所示:
My cat is named garfield
He is my first Cat
My mom is named cathy
This is a catastrophe
Hello how are you
我要檢查的字是貓
這是我寫的代碼:
input_file = sys.argv[1]
input_file = open(input_file,"r")
wordCheck = sys.argv[2]
for line in input_file:
if wordCheck in line:
print line
input1.close()
現在顯然,這將返回第1、3和4行,因為它們在某些時候都包含“ cat”。 我的問題是,我將如何工作以便僅打印第1行(僅帶有單詞“ cat”的行)?
第二個問題是,不管大小寫如何,獲取其中包含“ cat”一詞的所有行的最佳方法是什么? 因此,在這種情況下,您將返回行1和2,因為它們分別包含“ cat”和“ Cat”。 提前致謝。
您可以為此使用正則表達式 :
import re
# '\b': word boundary, re.I: case insensitive
pat = re.compile(r'\b{}\b'.format(wordCheck), flags=re.I)
for line in input_file:
if pat.search(line):
print line
這是一種簡單的方法,可以直接在單詞列表中使用in
而不是直接在字符串中使用。
word = 'cat'
for line in lines:
if word in line.split(' '): # use `in` on a list of all the words of that line.
print(line)
輸出: My cat is named garfield
對於第一個問題,您可以使用break
語句在獲得第一個匹配項后停止循環
for line in input_file:
if wordCheck in line.split(' '):
print line
break # add break here
對於第二個問題,您可以使用lower()
函數將所有內容都轉換為小寫,以便可以檢測到Cat
和cat
。
for line in input_file:
if wordCheck in line.lower().split(' '):
print line
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.