如何获取文本文件中使用特定2个字符的次数(例如('hi')) 如何将总和打印为int?
我试过这样做:
for line in open('test.txt'):
ly = line.split()
for i in ly:
a = i.count('ly')
print(sum(a))
但它失败了,先谢谢!
答案 0 :(得分:2)
您的程序失败,因为您的变量 a 是一个整数,并且您无法将 sum 函数应用于整数。 已经提出了几个例子。这是我的:
with open("test.txt") as fp:
a = fp.read().count('ly')
print(a)
答案 1 :(得分:1)
不同的方法:
from collections import Counter
text = open('text.txt').read()
word_count = Counter(text.split())
print word_count['hi']
答案 2 :(得分:1)
你可以简单地在每一行上计算'ly':
sum(line.count('ly') for line in open('test.txt'))
答案 3 :(得分:0)
for line in open('test.txt'):
ly = line.split()
alist = [i.count('hi') for i in ly]
print sum(alist)
答案 4 :(得分:0)
您可以尝试这样的事情
for line in open('test.txt'):
ly = line.split()
for i in ly:
if 'word' in i:
a = a + 1
print (a)