我刚开始编程。我正在做一个项目,在这个项目中,我计算出一篇文章或一部小说中出现了多少个单词,程序会打印出这个单词,以及它在文章中被重复了多少次。我在程序中使用词典。在
之后,我提示用户插入一个单词,程序将尝试查找该单词出现的次数(如果有的话)。但是,我对上一个else语句有一个问题。如果单词不存在,则“print(单词不存在于插入的文件中”)”会反复出现。如何解决它,使它只打印一次?在
这是我的代码: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()