【问题标题】:loop not incrementing in list python循环不在列表python中递增
【发布时间】:2013-12-12 12:18:22
【问题描述】:

我在标准输入中获取一个文件,看起来像

12    125      "neg"       Won the match #getin . P

然后对句子进行单词分析。

我不知道为什么,但是函数“unigrams_nrc”中的循环没有增加。 i value is still 0

代码如下:

def unigrams_nrc(file):
      for line in file:
      (term,score,numPos,numNeg) = re.split("\t", line.strip())
      print sentence[i] #=> prints all 0's i does not increment
      if re.match(sentence[i],term.lower()):
         wordanalysis["unigram"] = found
      else:
         found = False
      if found:
         wordanalysis["trail_unigram"] = found if re.match(sentence[(len(sentence)-1)],term.lower()) else not(found)
         wordanalysis["lead_unigram"] = found  if re.match(sentence[0],term.lower()) else not(found)
         wordanalysis["nonzero_sscore"] = float(score) if (float(score) != 0) else 0             
         wordanalysis["sscore>0"] = (float(score) > 0)
         wordanalysis["sscore"] = (float(score) != 0)

      if re.match(tweet[len(sentence)-1],term.lower()):
         wordanalysis["sscore !=0 last token"] = (float(score) != 0)


for line in sys.stdin:
    #12    125    "neg"       Won the match #getin . P
   (tweetid,num,senti,tweets) = re.split("\t+",line.strip())
   sentence = re.split("\s+", tweets.strip())
   for i in range(0,len(sentence)):
      unigrams_nrc(file)

即使我将参数中的i 传递给函数.. 仍然没有变化。

【问题讨论】:

  • unigrams_nrc 是函数
  • 不是i是0,是sentence[i]
  • 怎么可能,我的意思是你甚至没有打开你的代码示例中的文件。
  • @GamesBrainiac 我还没有发布那部分代码。我认为这很明显
  • 您目前也有缩进错误。例如,for line in file: 之后的代码没有缩进,所以我们不知道它在那个块中是什么,什么不是。

标签: python file for-loop file-io


【解决方案1】:

缩进不正确,但假设它应该像in your other questionprint sentence[i]for line in file: 循环内。由于i 没有在循环内递增,您会看到多次打印相同的内容。

当您第二次调用unigrams_nrc 时,file 中没有更多行可读取,因此循环执行零次。要再次读取该文件,您需要关闭并打开它,或者将seek 重新打开。虽然,将数据读入例如。一本字典,甚至只是一个列表,都会加快你的程序。

快速解决方法是在打开file 后添加file = file.readlines();你的其余代码应该可以正常工作。

【讨论】:

  • 仅打印 Won 'n' 次
  • 是的,我知道 i 没有增加,但为什么会这样。我该如何解决这个问题。
【解决方案2】:

你想做这样的事情

def foo1():
    print something[i]

def foo0():
    for i in range(0,number):
        foo1(somethingElse)

这是不可能的!
foo1 应该如何知道isentence 的值?如果你想使用它们,你必须传递这些值。

def foo1(something,i):
    print something[i]

def foo0():
    for i in range(0,number):
        foo1(something,i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多