【问题标题】:python argument of type 'int' is not iterable when using for in使用 for in 时,'int' 类型的 python 参数不可迭代
【发布时间】:2018-03-29 19:49:10
【问题描述】:

我正在尝试编写从命令行接受文件名的代码,并且 打印出以下属性:

  • 行数
  • 字符数
  • 字数
  • “该”的数量
  • “a/an”的数量

我不断收到错误消息

“'int'类型的参数不可迭代”

if 'the' in words: 行。

我该如何解决这个问题?

import sys
import string

file_name=sys.argv[0]

char= words = lines = theCount = aCount= 0

with open(file_name,'r') as in_file:
    for line in in_file:
        lines +=1
        words +=len(line.split())
        char +=len(line)
        if 'the' in words:
            theCount +=1
        if 'a' in words:
            a +=1
        if 'an' in words:
            a +=1

print("Filename:", file_name)
print("Number of lines:", lines)
print("Number of characters:", char)
print("Number of 'the'", theCount)
print("Number of a/an:", aCount)

【问题讨论】:

  • 请参阅官方文档中的 this Counter 配方,其中展示了如何做大部分您想做的事情。

标签: python python-3.x


【解决方案1】:

如果您尝试收集实际单词,而不仅仅是它们的计数,那么您可能需要将单词初始化为一个空列表:

words = []

改变

words += len(line.split())

words += line.split()

【讨论】:

    【解决方案2】:

    您的代码中有一些错误,请阅读此片段中的 cmets:

    import sys
    #import string   #not sure if this is needed
    
    file_name=sys.argv[0]
    
    char= words = lines = theCount = aCount= 0
    
    
    with open(file_name,'r') as in_file:
        for line in in_file:
            lines +=1
            x = line.split() #use a variable to hold the split words
                             #so that you can search in it
            words +=len(x)
            char +=len(line)
            if 'the' in x:   #your original code was using "words" variable
                             #that holds the "number of words" in the line,
                             #therefore ints are not iterable
                theCount +=1
            if 'a' in x:
                aCount +=1   #your original code using "a" variable 
                             #which did not initialized, 
                             #you have initialized "aCount" variable
            if 'an' in x:
                aCount +=1   #same as above
    
    print("Filename:", file_name)
    print("Number of lines:", lines)
    print("Number of characters:", char)
    print("Number of 'the'", theCount)
    print("Number of a/an:", aCount)
    

    https://repl.it/Mnwz/0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      • 2022-01-25
      • 2016-04-06
      • 1970-01-01
      • 2012-04-26
      相关资源
      最近更新 更多