2017-02-23 25 views
-3

我试图计算一行8个字符或更少,并计算小写“f”出现多少次。 f显示的次数值始终显示为零。 Text1.txt具有小写F“”一个时间在第1行和第4次第2行python字符数问题

with open("text1.txt","r+") as r: 
while True: 
     cCount = r.readlines(1) 
     charSet = cCount.count("f") 
     print charSet 
     if not cCount: 
      break 
if charSet == 1: 
    print("hello") 

哪里有我的Python逻辑失败。

+1

请妥善打算代码。 –

+0

有没有错误?结果无效?请解释您遇到的问题 – Sayse

回答

0

试试这个:

with open("text1.txt","r") as r: 
    for line in r: 
     print(line.count("f")) 

这是遍历文件

编辑的正确方法:改变 “fghfghf” 到 “3ghgh”

with open("text1.txt","r") as r: 
    for line in r: 
     if line.count("f")==3: 
      print("3"+line.replace("f","")) 
+0

感谢您user4624500这有助于显示每条线上有多少。 我该如何设置一个变量来说好吗?f等于3在第1行,所以用行首开头的三个替换f? python运行之前.-- fghfghf python运行后.-- 3ghgh – LetsChangeTheWorld

+0

我知道如何替换。(“f”,“3”)似乎我有问题堆叠命令ontop彼此而不必启动一个新的模块。再次感谢。 – LetsChangeTheWorld