我需要从文件中读取字母v被提及的次数。我其实知道一个事实,如果'v'是在这句话中,它将是第一个出现。我有它的方式设置它并按字符串计算字符串,这就是它如何写它,但我只想提一个句子提及在整个文件中提及'v'的次数。将字符串转换为整数并在Python中格式化代码
f = open("triangle.txt", 'r') #opens the given name file to read input
fw = open("convert.txt",'w') #opens the given name file to write in
for line in f:
data = line.strip().split(" ")
vertices=0
vertices =(str(data.count('v')))
fw.write("Number of vertices = " + vertices +'\n')
f.close()
fw.close()
我试图
vertices += int((str(data.count('v'))))
然而,这一直给我,我可以把字符串转换为整数的错误消息。 任何建议非常感谢。
对,我加入了它,我不记得伯爵会给我一个整数回来。问题出在我写的是逐行写,而不是总写。谢谢 – Luis