如果我删除这些代码行:
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()
答案 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ş")