Python 3:在文本文件中,获取在x出现的y行中出现的字符串

时间:2019-02-19 13:57:03

标签: python string

我有一个文本(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

我不明白出了什么问题。

预先感谢您的帮助

1 个答案:

答案 0 :(得分:2)

问题是if word in line:为{Berlin“时,True将返回word,并且该行包括” ... Berliner ...“,因为它作为“ [柏林]”。

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

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