我不知道此错误的原因,但我试图获取文件中的单词,读取行,拆分它们,然后将这些单词添加到列表中并对它们进行排序。这很简单,但我似乎收到一个错误,指出“'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)
结果应该打印出诗歌中出现的单词的排序列表。
白猪掌柜的
千巷猫影
慕标5832272
相关分类