gpt4 book ai didi

python - if else语句和python中的字典

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:48 24 4
gpt4 key购买 nike

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

之后,我提示用户插入一个词,程序将尝试查找该词出现的次数(如果有的话)。但是,我的最后一个 else 语句有问题。如果单词不存在,则“打印(“插入的文件中不存在该单词”)”一次又一次地重复。我怎样才能解决它只打印一次?

这是我的代码:

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()

最佳答案

我应该指出,您实际上根本不需要这个循环。字典的全部意义在于您可以直接通过关键字查找内容。所以:

try:
print(prompt, D[prompt])
except KeyError:
print("the word does not exist in the file inserted")

但让我们看看如何修复现有代码。

问题是您正在为字典中的每个键执行一次 if/else,并且每次 any 键匹配失败,而不是仅当没有键匹配失败时。

您可以使用 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")

但是,代码更多,出错的地方也更多。

关于python - if else语句和python中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20157108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com