2014-04-22 71 views
0

我有一個代碼,它接受一個文本文件並解析它以獲取每個單詞的頻率並將其存儲在字典中。在哪裏結束For循環

# Load a corpus and build a language model 
def load_model(filename): 
"""Loads a corpus file and builds a language model consisting of word:frequency. 
Converts all words to lowercase, strips punctuation, and ignores any non-alphabetic characters.""" 

    dictionary = {} 
    f = open(filename) 
    for line in f: 
     words = line.split(' ') # Split each word and iterate through. 
     for string in words: 

      for c in string: # Check each character value for punctuation or numeric type. 

       if c in Punct: 
        string = string.replace(c,"") 
       if c.isdigit() 
        print String + ' is not formattable.\n' 
        break 

      string = string.lower() 
      if string in dictionary: 
       dictionary[string] = dictionary[string] + 1 
      else: 
       dictionary[string] = 1 
    f.close() 
    return dictionary 

我的問題是我需要休息結束檢查整個字符串,而不僅僅是結束檢查字符。

是否斷頭路循環它位於或什麼時候結束第一循環:(「在F線」)

而且,繼續將簡單地結束這種特定的循環。

我想要它,以便它結束檢查整個字符串,它將移動到單詞中的下一個字符串。

+0

我可能不應該使用字符串作爲變量名。 – alvarezcl

+0

隨時編輯您自己的問題 – niklasfi

+4

休息結束最內層循環。 –

回答

1

documentation

break語句,像C,爆發最小的封閉 for或while循環。

this question,Python不支持結構像break 2,如PHP一樣。

1

break結束它所包含的最內層/即時循環,即它直接在其範圍內的那個循環。

for x in X: 
    for y in Y: 
     break 

x循環將運行至完成,該y循環將打破。

可以通過也許設置變量作爲一個標誌導致在外環休息:

break_outer = False 
for x in X: 
    for y in Y: 
     if condition: 
      break_outer = True 
      break 
    if break_outer: 
     break 

實施例:

for x in range(3): 
    for y in range(2): 
     if x == 2: 
      break 
     print "x =",x,"y =",y 

輸出:

>>> x = 0 y = 0 
>>> x = 0 y = 1 
>>> x = 2 y = 0 
>>> x = 2 y = 1 

並打破你可以通過一個外部循環變量:

break_outer = False 
for x in range(3): 
    for y in range(2): 
     if x == 2: 
      break_outer = True 
      break 
     print "x =",x,"y =",y 
    if break_outer: 
     break 

輸出:

>>> x = 0 y = 0 
>>> x = 0 y = 1 

continue跳過殘留在環和代碼的其餘部分繼續到下一次迭代中for循環:

for i in range(3): 
    if i == 1: 
     continue 
    print i 

輸出:

>>> 0 
>>> 2 

你的代碼似乎在做你在問什麼,break ing並轉移到下一個單詞......有沒有關於代碼產生不良結果的其他內容?

1

break將突破它所在的最內層循環。

您可以使用@farmerjoe建議的內容打破外部循環。

但我不明白你爲什麼想這樣做。您在那裏的break看起來很好,因爲它會停止處理當前字符串的字符,並繼續檢查下一個字符串。

代碼中存在一些錯誤。我修復它們給你和一些風格問題:

def load_model(filename): 
    dictionary = {} 
    with open(filename) as f: 
     for line in f: 
      words = line.split(' ') # Split each word and iterate through. 
      for word in words: 
       for c in word: # Check each character value for punctuation or numeric type. 
        if c in Punct: 
         word = word.replace(c, "") 
        if c.isdigit(): 
         print word + ' is not formattable.\n' 
         break 

       word = word.lower() 
       if word in dictionary: 
        dictionary[word] += 1 
       else: 
        dictionary[word] = 1 
    return dictionary