在python中,这可以完成工作:
#!/usr/bin/env python3
s = """How to get This line that this word repeated 3 times in THIS line?
But not this line which is THIS word repeated 2 times.
And I will get This line with this here and This one
A test line with four this and This another THIS and last this"""
for line in s.splitlines():
if line.lower().count("this") == 3:
print(line)
输出:
How to get This line that this word repeated 3 times in THIS line?
And I will get This line with this here and This one
或以文件作为参数从文件中读取:
#!/usr/bin/env python3
import sys
file = sys.argv[1]
with open(file) as src:
lines = [line.strip() for line in src.readlines()]
for line in lines:
if line.lower().count("this") == 3:
print(line)
当然,单词“ this”可以用任何其他单词(或其他字符串或行部分)代替,并且每行出现的次数可以设置为该行中的任何其他值:
if line.lower().count("this") == 3:
编辑
如果文件很大(数十万/百万行),则下面的代码会更快;它每行读取一次文件,而不是一次加载文件:
#!/usr/bin/env python3
import sys
file = sys.argv[1]
with open(file) as src:
for line in src:
if line.lower().count("this") == 3:
print(line.strip())