我收到了一个包含许多不同字母的txt文件。例如:
ab sbfdjd iojdig
ds fjk sdfji oer
lkjäp foküeeferf
我如何检查例如字母";j";在第1行、第2行和第3行中使用,并将此信息存储在数组/列表中?
因此,对于这个特定的例子
print(NumberOfJInLine[0])
将输出:
2
试试这个
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))
您不需要我添加的其他功能,但它增加了灵活性。
或者:
def AccumulateAppearances():
with open("text.txt", "r") as file:
for line in file:
yield line.count("j")
for n in AccumulateAppearances():
print(n)
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)
你可以用字典更容易地做到这一点