该程序检查它是否在用户收到的文件text.txt中

时间:2018-02-01 08:03:50

标签: python

如果我删除这些代码行:

else:
  print("Boş")
  break

然后,该程序似乎工作正常,但是当我再次添加它时,程序在text.txt中找不到任何单词并抛出Not found异常。

以下是完整代码:

class x():
         def __init__(self):
            with open('metin.txt', 'r', encoding="utf-8")as file:
                 icerik = file.read()
                 icerik = icerik.split()
                 self.sade_kelime = []
                 self.sozluk = dict()
                 file.seek(0)
                 for i in icerik:
                     i = i.strip(".")
                     i = i.strip(",")
                     i = i.strip("")
                     self.sade_kelime.append(i)
                 for i in self.sade_kelime:
                     if i in self.sozluk:
                        self.sozluk[i] += 1
                     else:
                         self.sozluk[i] = 1
          def kelime_frekans(self):
                 for i in self.sozluk:
                     if i == kelime:
                      print(kelime, self.sozluk[i], "kez metinde geciyor")
                     else:
                      print("Boş")
                      break
        dosya = x()
        while True:
             kelime = input('kelime:')
             if kelime == "q":
                 break
             else:
                 dosya.kelime_frekans()

1 个答案:

答案 0 :(得分:0)

if i == kelime条件在第一次迭代时不满足,循环将中断。 从逻辑上讲,这不是一个正确的代码。您的kelime_frekans函数应该是这样的:

def kelime_frekans(self):
        for i in self.sozluk:
            if i == kelime:
                print(kelime, self.sozluk[i], "kez metinde geciyor")
                return
        print("Boş")