2013-11-23 87 views
0

我刚开始编程。我正在制作一个项目,在这个项目中,我可以统计一篇文章或一本小说中出现的单词数量,然后程序会打印这个单词以及它在文章中重复的次数。我在程序中使用字典。if else语句和字典在Python中

之后,我提示用户插入一个单词,程序将尝试查找该单词发生了多少次(如果有的话)。不过,我的最后一条陈述有问题。如果该单词不存在,那么“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() 
+0

Python有于类别的东西,已经做了这个,仅供参考。 '这是一个无序的集合,元素被存储为字典键,并且它们的计数被存储为字典值。' http://docs.python.org/2/library/collections.html – cdhagmann

回答

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

这样一来,如果通过整个循环得到没有击中一个break,而不是引发的else才会触发每次通过循环,你不会中断。

对于一些人来说,这是一个棘手的概念(特别是来自其他语言的人不具备此功能),但教程部分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") 

但是,这是更多的代码,以及更多的地方出错。

0

我认为你从根本上误解字典是如何工作的。

他们是查找设备 - 给出key,去取value。想想:你用纸质词典做什么。你不扫描整个事物,阅读每一个字,直到你找到你要找的单词,是吗? (希望不是)

只需用你的词典就像是意在用于:

result = D.get(prompt) 
if result: 
    print(result) 
else: 
    print("doesn't exist")