计算文件文本中的co出现次数

时间:2016-04-26 21:41:38

标签: python python-2.7 python-3.x

我有一个列表,一个文件文本和一个字符串

list1 = ['man', 'girl', 'woman']
str = "work"
text_file

需要的是计算字符串的共同出现" work"对于list1中的每个项目,当它们都出现在text_file中的同一行时。

我试过这个

n_occurrence = 0
for line in text_file:
    for item in list1:
        if item in line and str in line:
            n_occurrence +=1

此代码使用列表中的所有元素计算str的出现次数,但我希望将str的出现与列表中的每个项目分开。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

试试这个

from collections import defaultdict
n_occurence = defaultdict(lambda:0)
for line in text_file:
    for item in list1:
        if item in line and str in line:
            n_occurence[item] +=1