我正在用Python编写一个程序,它将计算文件中的频繁字符。它所计算的字符由用户决定。我一直在收到这条消息,而且我一直在努力争取最长的时间来解决这个问题:
filename = open('all-Names.txt', 'r')
character = input("Enter character: ")
x = filename.count(character)
print(x)
filename.close()
答案 0 :(得分:1)
文件对象上没有count()
方法。您应该遍历文件行并总结每行的计数:
character = input("Enter character: ")
with open('all-Names.txt', 'r') as f:
print(sum(line.count(character) for line in f))
演示:
$ cat all-Names.txt
test
test2
test3
test4
test5
$ python
...
>>> character = input("Enter character: ")
Enter character: t
>>> with open('all-Names.txt', 'r') as f:
... print(sum(line.count(character) for line in f))
...
10