如何返回仅包含特定单词的行

运行一个简单的程序,它接受两个输入、一个输入文件和一个要搜索的词。然后它应该打印出包含该单词的所有行。例如,我的输入文件包含 5 个句子,如下所示:


My cat is named garfield

He is my first Cat

My mom is named cathy

This is a catastrophe

Hello how are you

我要检查的词是 cat


这是我写的代码:


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”。提前致谢。


ibeautiful
浏览 189回答 3
3回答

BIG阳

您可以为此使用正则表达式: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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python