600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python中else和if的结合语句_python中else和if的结合语句_python中的if-else语句和字典...

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

时间:2018-10-02 12:14:12

相关推荐

python中else和if的结合语句_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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。