我刚刚开始编程。我正在制作一个项目,我可以计算文章或小说中出现的单词数量,程序会打印出单词以及文章中重复的次数。我在程序中使用词典。
之后,我提示用户插入一个单词,程序将尝试查找该单词出现的次数(如果有的话)。但是,我的上一个其他声明有问题。如果该单词不存在,则“一次又一次地重复”打印(“插入的文件中不存在该单词”)。我怎么解决它只打印一次?
这是我的代码:
from string import *
import codecs
def removePunctuation(sentence):
new_sentence = ""
for char in sentence:
if char not in punctuation:
new_sentence = new_sentence + char
return new_sentence
def wordFrequences(new_sentence):
wordFreq = {}
split_sentence = new_sentence.split()
for word in split_sentence:
wordFreq[word] = wordFreq.get(word,0) + 1
wordFreq.items()
return (wordFreq)
#=====================================================
def main():
fileName = open("arabic.txt","r")
#fileName = open("arabic.txt","r",encoding="utf-8")
new_sentence = removePunctuation(fileName)
D = wordFrequences(new_sentence)
#print(D)
excel = open("file.csv", "w")
excel.write("words in article" + "\t" + "frequency" + "\n\n")
for i in D:
#print(i , D[i])
excel.write(i + "\t" + str(D[i]) + "\n")
prompt = input("insert a word for frequency: ")
found = True
for key in D:
if key == prompt:
print(key, D[key])
break
else:
print("the word does not exist in the file inserted")
main()
答案 0 :(得分:4)
我应该指出你实际上根本不需要这个循环。字典的重点是你可以直接用键来查找。所以:
try:
print(prompt, D[prompt])
except KeyError:
print("the word does not exist in the file inserted")
但是,让我们来看看如何修复现有代码。
问题在于,您为字典中的每个键执行if
/ else
一次,并且每次任何键无法匹配时打印该输出,而不仅仅是没有键无法匹配。
您可以使用for
/ else
代替if
/ else
来解决此问题:
for key in D:
if key == prompt:
print(key, D[key])
break
else:
print("the word does not exist in the file inserted")
这样,只有在没有点击else
的情况下完成整个循环,break
才会触发,而不是每次都通过你没有中断的循环触发。
对于某些人来说,这是一个棘手的概念(特别是来自其他没有此功能的语言的人),但教程部分break
and continue
Statements, and else
Clauses on Loops很好地解释了这一点。
或者,你有Found
标志;你实际上可以使用它:
found = False
for key in D:
if key == prompt:
print(key, D[key])
found = True
break
if not found:
print("the word does not exist in the file inserted")
然而,这是更多的代码,还有更多地方可以解决问题。
答案 1 :(得分:0)
我认为你从根本上误解了词典是如何运作的。
他们是一个查找设备 - 给定key
,请获取value
。想想:你用纸质词典做什么。你不会扫描整个事物,阅读每一个字,直到找到你要找的字,是吗? (希望不是)
只需使用您想要使用的词典:
result = D.get(prompt)
if result:
print(result)
else:
print("doesn't exist")