2015-10-05 69 views
0

我需要从文件中读取字母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')))) 

然而,这一直给我,我可以把字符串转换为整数的错误消息。 任何建议非常感谢。

回答

0

首先,如果你想要一个句子提到的次数“ v'被提及,简单地写这行

fw.write("Number of vertices = " + vertices +'\n') 

失去for循环。其次,

data.count('v') 

会给你一个int值作为输出,所以你不必先将它转换为字符串,然后回到整数。这里是修改后的代码;

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 
vertices=0 
for line in f: 
    data = line.strip().split(" ") 
    vertices += ((data.count('v'))) 
fw.write("Number of vertices = " + str(vertices) +'\n') 

f.close() 
fw.close() 

此外,如果在句子中提及单词时,您的代码只计数'v'。要计算'v'发生的总次数,请使用@bad_keypoints建议的值。

+0

对,我加入了它,我不记得伯爵会给我一个整数回来。问题出在我写的是逐行写,而不是总写。谢谢 – Luis

0

如果你只是想知道的次v数量在文件中所提到的,你为什么不简单的做到这一点:

with open('file.dat', 'r+') as f: 
    v_count = f.read().count('v') 
+0

所以使用这段代码,它会按照我期待的方式计算v的数量,但是当我尝试在同一时间计算另一个字母时,它只返回顶部行,例如 with open('file.dat', 'r +')为f: f: f_count = f.read()。count('f') v_count = f.read()。count('v') 只会给我个数的时间'f'被计数,而不是'v' – Luis

+0

@Luis这不是黑魔法。这就是'读'的工作原理。它一次读取整个文件。您可以将读取的内容放入另一个变量中,然后对所有其他字符串进行计数。 –