为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
陪伴而非守候 2022-01-18 13:48:28
我不知道此错误的原因,但我试图获取文件中的单词,读取行,拆分它们,然后将这些单词添加到列表中并对它们进行排序。这很简单,但我似乎收到一个错误,指出“'str'对象不能被解释为整数'我不知道这个错误的原因,希望能得到一些帮助。我没有尝试过很多方法,因为我确信这个方法会起作用,而且我不知道如何绕过它。我正在使用的文件包含以下内容:But soft what light through yonder window breaksIt is the east and Juliet is the sunArise fair sun and kill the envious moonWho 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)结果应该打印出诗歌中出现的单词的排序列表。
查看完整描述

3 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

您巨大的 try/except 块会阻止您查看错误的来源。删除:


› python romeo.py 

Traceback (most recent call last):

  File "romeo.py", line 9, in <module>

    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'。


查看完整回答
反对 回复 2022-01-18
?
千巷猫影

TA贡献1829条经验 获得超7个赞

当您拆分f = line.split(' ', '/n')而不是执行此操作时会导致错误f = line.split('\n')[0].split(' ')。同样在下一个声明中,我认为您会extend不想append


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')[0].split(' ')   ##<-first error


        l.extend(f)                          ##<- next problem


    k = set(sorted(l))


    print(k)


except Exception as e:

    print(e)

虽然,一个更好的实现:


l = [] # empty list


with open('romeo.txt') as file:


    for line in file:

        f = line[:-1].split(' ')

        l.extend(f)


    k = set(sorted(l))

    print(k)


查看完整回答
反对 回复 2022-01-18
?
慕标5832272

TA贡献1966条经验 获得超4个赞

您可能应该with在这种情况下使用。它本质上管理您原本不受管理的资源。这是一个很好的解释:python 关键字“with”用于什么?.


至于你的问题:


with open(fname, "r") as f:

    words = []

    for line in f:

        line = line.replace('\n', ' ')

        for word in line.split(' '):

            words.append(word)

这将逐行读取文本并将每行拆分为单词。然后将单词添加到列表中。


如果您正在寻找更短的版本:


with open(fname, "r") as f:

    words = [word for word in [line.replace('\n', '').split(' ') for line in f]]

这将给出每个句子的单词列表,但是您可以以这种方式展平并获取所有单词。


查看完整回答
反对 回复 2022-01-18
  • 3 回答
  • 0 关注
  • 223 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号