python 中的字符串到整数和格式化代码

string to integer and formating code in python

我需要从文件中读取字母 v 被提及的次数。我实际上知道一个事实,如果 'v' 在那句话中,它将是第一个出现的东西。我设置它的方式是逐个字符串计数,这就是它的编写方式,但我只想用一句话来提及整个文件中提到 'v' 的次数。

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'))))

然而,它一直给我一条错误消息,提示我无法将字符串转换为整数。 非常感谢任何建议。

如果您只是想知道文件中提到 v 的次数,为什么不简单地这样做:

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

首先,如果你想要一个提到次数 '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 建议的内容。