面对错误TypeError:总计数时'int'对象不可迭代
问题描述:
我有一个任务来计算来自多个文本文件的符号。我即将完成,但面临一个问题。以下是我的n我想总结commaCount
的值。我把命令total = sum(commacount)
但它显示错误面对错误TypeError:总计数时'int'对象不可迭代
total = sum(commaCount)
TypeError: 'int' object is not iterable
这里是我的代码:
import glob
def stats():
commaCount = 0
path = 'D:/Stiudies/Data/female/*.txt'
inf = glob.glob(path)
for name in inf:
with open(name, 'r', encoding="utf8") as input_file:
for line in input_file:
for char in line:
if char == ',':
commaCount += 1
total = sum(commaCount)
print(commaCount)
stats()
答
使用计数功能:
a = "hi, hello, good by, , ,"
print(a.count(","))
它会告诉你:
但对于你的原代码:
path = 'D:/Stiudies/Data/female/*.txt'
inf = glob.glob(path)
buffer_commas = 0
for name in inf:
with open(name, 'r', encoding="utf8") as input_file:
raw_data = input_file.read()
buffer_commas = buffer_commas + raw.count(",")
print(buffer_commas)
答
错误来形成内置sum功能需要接收一个说法,有点像一个列表的事实数字(“可迭代”),它将汇总在一起。在你的情况下,你给它commaCount
,这是一个单一的数字(不可迭代)。
但是,通过使用:
commaCount += 1
你已经总结了所有的一切文件的逗号的,所以没有理由这样做的另一个sum
。我想你可以删除那一行。这样
答
下面的代码有助于查找号码','每个文件和总共文件列表
import glob
path = 'D:\Stiudies\Data\female\*.txt'
inf = glob.glob(path)
commaCount = 0
for name in inf:
with open(name, 'r') as input_file:
count += input_file.read().count(',')
print "Count:{}\t for file:{}:".format(count,name)
commaCount +=count
print "Total count:", commaCount
谢谢你的帮助代码工作正常。我也想统计大写字母。请帮助我。谢谢。 –
@MuhammadHafizTahir:使用print(sum(1(对于your_string中的c,如果c.isupper())) – DRPK