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

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)

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]]
这将给出每个句子的单词列表,但是您可以以这种方式展平并获取所有单词。
- 3 回答
- 0 关注
- 223 浏览
添加回答
举报