首页 文章

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

提问于
浏览
1

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

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 回答

  • 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
    

相关问题