简体   繁体   English

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

[英]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.

相关问题 Python-从文本文件中获取行,行xy - Python - grab lines from text file, lines x-y 使用Python 2.7在出现字符串的位置拆分文本文件 - Split a text file at where a string occurs using Python 2.7 Python-输入文件中出现字符串的所有行和行号 - Python - All the lines and line numbers in which string occurs in the input file 如何在另一个文本文件中的Y行中查找和替换一个文本文件中的X行? - How to find and replace X lines in one text file with Y lines in another text file? 获取文件中出现字符串的倒数第四行 - Get fourth to last line where a string occurs in a file Python 得到字符串的 position 和接下来的 X 行 - Python get position of string and the next X lines 如何检查文本文件的每一行是否有字符串并将所有出现该单词的行打印到新文本文件中? - How to check each line of a text file for a string and print all lines with occurrences of that word to a new text file? 创建一个字典,将文本文件的每个单词链接到文件中出现的行的列表 - Creating a dictionary linking each word of a text file to a list of lines where it occurs in the file Python搜索文本文件并计算指定字符串的出现次数 - Python search text file and count occurrences of a specified string 识别文本中出现单词的行并将这些行保存在列表中 - Identify lines where word occurs in a text and save the lines in a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM