Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3:在文本文件中,获取字符串在y行中出现的x个位置_Python_String - Fatal编程技术网

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

Python 3:在文本文件中,获取字符串在y行中出现的x个位置,python,string,Python,String,我有一个文本(countevents.txt) 我想计算字符串在其出现的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 wor

我有一个文本(countevents.txt)

我想计算字符串在其出现的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
我不明白出了什么问题


提前感谢您的帮助

问题是
如果行中的word:
将在
word
为“Berlin”时返回
True
,行中包括“…Berliner…”,因为它作为“[Berlin]er”的子字符串存在

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

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