python中else和if的结合语句_python中的if-else语句和字典

我刚开始编程。我正在做一个项目,在这个项目中,我计算出一篇文章或一部小说中出现了多少个单词,程序会打印出这个单词,以及它在文章中被重复了多少次。我在程序中使用词典。在

之后,我提示用户插入一个单词,程序将尝试查找该单词出现的次数(如果有的话)。但是,我对上一个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()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值