首页 > 解决方案 > Python 3:在文本文件中,获取字符串在其出现的 y 行中出现的 x 次

问题描述

我有一个文本 (CountOccurrences.txt)

Paris Rome
berlin London Berlin
London Rome London
Paris Berlin Berlin
Rome London
Berlin Madrid
Parisian Berliner

我想计算一个字符串在它出现的 y 行中出现的 x 次。

这是我的代码

f = open('CountOccurrences.txt')

word = input("Enter word to be looked for : ")

oc = 0
li = 0

for line in f:

    if word in line:
        li = li + 1

    words = line.split()
    for i in words:
        if(i==word):
            oc = oc + 1

print('Considering that this search is case-sensitive, \
there are', oc, 'occurrence(s) of the word, \
in', li, 'line(s)')

f.close

这是每个单词的结果,如您所见,有两个问题:

Berlin       4 oc, 4 li (pb)
berlin       1 oc, 1 li
Berliner     1 oc, 1 li
London       4 oc, 3 li
Madrid       1 oc, 1 li
Paris        2 oc, 3 li (pb)
Parisian     1 oc, 1 li
Rome         3 oc, 3 li

我不明白出了什么问题。

在此先感谢您的帮助

标签: pythonstring

解决方案


问题是何时if word in line:返回“Berlin”,并且该行包含“... Berliner...”,因为它作为“[Berlin]er”的子字符串存在。 Trueword

相反,请在拆分行后进行检查,如下所示:

for line in f:
    words = line.split()
    for i in words:
        if(i==word):
            oc = oc + 1

    if word in words: # modified part
        li = li + 1

推荐阅读