3 回答

TA贡献1859条经验 获得超6个赞
您可以为此使用正则表达式:
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

TA贡献1784条经验 获得超8个赞
这是一个简短的方法,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

TA贡献1809条经验 获得超8个赞
对于您的第一个问题,您可以使用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
添加回答
举报