猿问

将文件中的单词拆分并添加到列表中,“str”对象不能解释为整数错误

我不知道此错误的原因,但我试图获取文件中的单词,读取行,拆分它们,然后将这些单词添加到列表中并对它们进行排序。这很简单,但我似乎收到一个错误,指出“'str'对象不能被解释为整数'我不知道这个错误的原因,希望能得到一些帮助。


我没有尝试过很多方法,因为我确信这个方法会起作用,而且我不知道如何绕过它。我正在使用的文件包含以下内容:


But soft what light through yonder window breaks

It is the east and Juliet is the sun

Arise fair sun and kill the envious moon

Who is already sick and pale with grief

这是我正在使用的代码...




#userin = input("Enter file name: ")


try:

  l = [] # empty list


  relettter = open('romeo.txt', 'r')

  rd = relettter.readlines() 


  # loops through each line and reads file

  for line in rd:


    #add line to list

    f = line.split(' ', '/n')


    l.append(f)


  k = set(l.sort())


  print(k)


except Exception as e:

    print(e)

结果应该打印出诗歌中出现的单词的排序列表。


陪伴而非守候
浏览 224回答 3
3回答

白猪掌柜的

您巨大的 try/except 块会阻止您查看错误的来源。删除:› python romeo.py&nbsp;Traceback (most recent call last):&nbsp; File "romeo.py", line 9, in <module>&nbsp; &nbsp; f = line.split(' ', '/n')TypeError: 'str' object cannot be interpreted as an integer您将 '/n' 作为第二个参数传递给 split() 方法,它是一个 integer maxsplit。你的线f = line.split(' ', '/n')不起作用,因为 split 方法只能使用一个字符串,例如:f = line.split(' ')另请注意,'\n' 是换行符,而不是 '/n'。

千巷猫影

当您拆分f = line.split(' ', '/n')而不是执行此操作时会导致错误f = line.split('\n')[0].split(' ')。同样在下一个声明中,我认为您会extend不想appendtry:&nbsp; &nbsp; l = [] # empty list&nbsp; &nbsp; relettter = open('romeo.txt', 'r')&nbsp; &nbsp; rd = relettter.readlines()&nbsp;&nbsp; &nbsp; # loops through each line and reads file&nbsp; &nbsp; for line in rd:&nbsp; &nbsp; &nbsp; &nbsp; #add line to list&nbsp; &nbsp; &nbsp; &nbsp; f = line.split('\n')[0].split(' ')&nbsp; &nbsp;##<-first error&nbsp; &nbsp; &nbsp; &nbsp; l.extend(f)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ##<- next problem&nbsp; &nbsp; k = set(sorted(l))&nbsp; &nbsp; print(k)except Exception as e:&nbsp; &nbsp; print(e)虽然,一个更好的实现:l = [] # empty listwith open('romeo.txt') as file:&nbsp; &nbsp; for line in file:&nbsp; &nbsp; &nbsp; &nbsp; f = line[:-1].split(' ')&nbsp; &nbsp; &nbsp; &nbsp; l.extend(f)&nbsp; &nbsp; k = set(sorted(l))&nbsp; &nbsp; print(k)

慕标5832272

您可能应该with在这种情况下使用。它本质上管理您原本不受管理的资源。这是一个很好的解释:python 关键字“with”用于什么?.至于你的问题:with open(fname, "r") as f:&nbsp; &nbsp; words = []&nbsp; &nbsp; for line in f:&nbsp; &nbsp; &nbsp; &nbsp; line = line.replace('\n', ' ')&nbsp; &nbsp; &nbsp; &nbsp; for word in line.split(' '):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; words.append(word)这将逐行读取文本并将每行拆分为单词。然后将单词添加到列表中。如果您正在寻找更短的版本:with open(fname, "r") as f:&nbsp; &nbsp; words = [word for word in [line.replace('\n', '').split(' ') for line in f]]这将给出每个句子的单词列表,但是您可以以这种方式展平并获取所有单词。
随时随地看视频慕课网APP

相关分类

Go
我要回答