简体   繁体   中英

How often does xy occur in a line of a txt file? In Python

I am provided with a txt file including lots of different letters. eg:

ab sbfdjd iojdig
ds fjk   sdfji oer
lkjäp   foküeeferf

How can I check how often for example the letter "j" was used in line 1, line 2 and line 3 and store this information in an array/list?

So for this certain example

print(NumberOfJInLine[0])

would output:

2
seekLetter = "j"
occur = {}

with open("{your filename}", "r") as file:
    for nbLine,line in enumerate(file):
        occur[nbLine] = line.count(seekLetter)

for line in occur.keys():
    print("line {0} : ".format(line) + str(occur[line]) + seekLetter)

you can do it more easily with a dictionary

Try this

def NumberOfStringInLine(index, string_to_find):
    print(string_to_find, lines_of_file[index])
    return lines_of_file[index].count(string_to_find)

def NumberOfJInLine(index):
    return NumberOfStringInLine(index, "j")


lines_of_file = open("text.txt", "r").readlines()
print(NumberOfStringInLine(0, "jd"))
print(NumberOfJInLine(0))

You don't need the other function I added but it adds flexibility.

Alternatively:

def AccumulateAppearances():
    with open("text.txt", "r") as file:
        for line in file:
            yield line.count("j")

for n in AccumulateAppearances():
    print(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM