[英]Python 3 : in a text file, get the x occurrences of a string in the y lines where it occurs
I have a text (CountOccurrences.txt) 我有一个文本(CountOccurrences.txt)
Paris Rome
berlin London Berlin
London Rome London
Paris Berlin Berlin
Rome London
Berlin Madrid
Parisian Berliner
I want to count the x occurrences of a string in the y lines where it occurs. 我想计算一个字符串在y行中出现的x次。
Here is my code 这是我的代码
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
Here are the results for each word, with, as you can see, 2 problems : 这是每个单词的结果,如您所见,有两个问题:
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
I do not understand what goes wrong. 我不明白哪里出了问题。
Thanks in advance for your help 在此先感谢您的帮助
The problem is if word in line:
will return True
when word
is "Berlin", and the line includes "... Berliner..." because it exists as a substring of the "[Berlin]er". 问题是
if word in line:
当word
为“柏林”且该行包含“ ...柏林人...”时将返回True
,因为该行作为“柏林”的子串存在。
Instead, do the check after splitting the line as follows: 相反,请按如下所示拆分行后进行检查:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.