2014-04-22 72 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