[英]Count occurrences of string in lines with boolean AND
我是Python的新手,但需要读取文本文件的行并使用布尔AND来计算多个字符串的出现次数。 例如,如果特定行包含“蓝色”和“绿色”,我需要计算这是正确的行数。 到目前为止,这就是我所拥有的。
import re
file = open("text.txt")
lines = file.readlines()
print(lines.count('blue')
file.close()
感谢您的协助。
使用正则表达式 :
import re
count = 0
with open(filename, "r") as infile:
for line in infile:
if re.search(r"\bblue\b", line, flags=re.IGNORECASE) and re.search(r"\bgreen\b", line, flags=re.IGNORECASE):
count += 1
print(count)
\\b
表达式边界 这是忽略大小写时匹配整个单词的一种方法。 因此,例如,蓝莓或温室将不会被捕获。
我们在这里使用的技巧是检查set
的一行字是的超集{'blue', 'green'}
import re
from io import StringIO
mystr = StringIO("""animal door read blue
green purple blue yellow
dolphin giraffe turtle blue
life green battle blue""")
counter = 0
# replace mystr with open('file.txt', 'r')
with mystr as fin:
for line in fin.readlines():
words = set(line.rstrip('\n').lower().split())
if words >= {'blue', 'green'}:
counter += 1
print(counter) # 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.