从文件中删除特定单词。

时间:2016-10-17 22:03:42

标签: python-3.x

我在第12行遇到以下代码问题,得到错误'int'对象不可订阅。我只是不确定如何解决它。任何帮助,将不胜感激。

fname = input('Enter File:')
fhand = open(fname)
lst = list()
words = 0

for line in fhand:
    line = line.strip()
    if not line.startswith("Subject:Sakai"): continue
    words = line.split()
    revNumber = words[4]

if not words[6] =="in ":
    source = words[6].split("/")
    finalSrc = source[0]
    lst.append((revNumber,finalSrc))

else:
    source = words[7].split("/")
    finalSrc = source[0]
    lst.append((revNumber,finalSrc))

for revNumber,finalSrc in lst:
    print(revNumber,finalSrc)

print("There were",len(lst),"Subject lines in the file")enter code here

1 个答案:

答案 0 :(得分:1)

显然没有行.startswith("Subject:Sakai")所以你继续按继续而你永远不会到达words = line.split(),你的代码开头就有words = 0所以{{1导致你的错误,因为 words 仍然指向一个不是列表的整数。

if not words[6] =="in "

我认为你的代码实际上更像是:

In [1]: words = 0

In [2]: words[6]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-fe50e40ed82c> in <module>()
----> 1 words[6]

TypeError: 'int' object is not subscriptable

你在循环中进行检查。您也不需要在Python中声明变量,因此您可以完全删除 words = 0 。您仍然遇到没有行for line in fhand: line = line.strip() if not line.startswith("Subject:Sakai"): continue words = line.split() revNumber = words[4] if not words[6] =="in ": source = words[6].split("/") finalSrc = source[0] lst.append((revNumber,finalSrc)) else: source = words[7].split("/") finalSrc = source[0] lst.append((revNumber,finalSrc)) for revNumber,finalSrc in lst: print(revNumber,finalSrc) 但没有看到您必须自己弄明白的内容的问题。可能需要删除前导空格startswith("Subject:Sakai")或意图使用if not line.lstrip().startswith("Subject:Sakai"):