python - 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
我不明白出了什么问题。
在此先感谢您的帮助
解决方案
问题是何时if word in line:
返回“Berlin”,并且该行包含“... Berliner...”,因为它作为“[Berlin]er”的子字符串存在。 True
word
相反,请在拆分行后进行检查,如下所示:
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
推荐阅读
- hibernate - 无法删除或更新父行:从具有 2 个子级的中间父级删除条目时,外键约束失败
- python - 激活阿拉伯语翻译后,Django 表单占位符和标签未翻译
- sql - 有没有办法将 json 元素转换成不同的行?
- ios - 无法使用 AWSMobileClient iOS 登录。获取 AWSMobileClientError 错误 13
- html - 如何使用 CSS 删除输入字段的最后一个字母的字母间距?
- node.js - 使用 nodejs 从 cloud firestore 获取数据需要很长时间
- android - 运行模拟器的架构
- spring-boot - 连接到 IDE 中现有的 hsqldb 实例
- python - 将变量设置为 True 或 False 有什么意义?
- python - Pandas:将数据框的单元格与不同列的内容进行比较并复制相邻数据