首页 > 解决方案 > 如何解决“'NoneType'类型的参数不可迭代”的问题?

问题描述

我试图解决一个 Python 练习,但我的程序在运行时崩溃了。

练习指导如下:

打开文件 romeo.txt 并逐行读取。对于每一行,使用 split() 方法将该行拆分为一个单词列表。该程序应该建立一个单词列表。对于每行上的每个单词,检查该单词是否已经在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对生成的单词进行排序和打印。

这是我的代码:

fname = input("Enter file name: ")
fh = open(fname)
j=-1
glolist=list()
for line in fh:
    line=line.rstrip()
    lst=line.split()
    nb=len(lst)
    i=0
    while i< nb:
        if lst[i] not in glolist:    #argument of type 'NoneType' is not iterable"
            i=i+1
        else:
            j=i
            i=i+1
    if j==-1:
        glolist=glolist+lst
    else:
        h=0
        while h<j:
            glolist=lst.append(lst[h])
            h=h+1
        h=h+1
        while h<nb:
            glolist=lst.append(lst[h])
            h=h+1
glolist=glolist.sort()
print(glolist)

标签: python

解决方案


fname = input("Enter file name: ")
fh = open(fname)
words=list()
for line in fh:
    line=line.rstrip()
    lst=line.split()
    i=0
    while i<len(lst):
        str=lst[i]
        if str in words:
            i=i+1
        else:
            words.append(str)
            i=i+1
words.sort()
print(words)

推荐阅读