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 關注
- 215 瀏覽
添加回答
舉報