[英]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.我得到了一个包含许多不同字母的 txt 文件。 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?如何检查例如字母“j”在第 1、第 2 和第 3 行中使用的频率并将此信息存储在数组/列表中?
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.