嘗試讀取檔案然后將其存盤在串列中但未獲得所需的輸出:
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
#line = line.rstrip()
words = line.split()
if words not in lst:
lst.append(words)
lst.sort()
print(lst)
我的輸出:
[['Arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon'], ['but', 'soft', 'what', 'light ', 'through', 'yonder', 'window', 'breaks'], ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the '、'太陽']、['誰'、'是'、'已經'、'生病'、'和'、'蒼白'、'與'、'悲傷']]
期望的輸出:
['起來','但是','它','朱麗葉','誰','已經','和','休息','東方','羨慕','公平','悲傷','是'、'殺'、'光'、'月'、'蒼白'、'病'、'軟'、'太陽'、'之'、'透'、'什么'、'窗'、'有' , '那邊']
uj5u.com熱心網友回復:
您所要做的就是遍歷句子中的所有單詞,然后檢查它們是否已經在串列中,然后附加它們。
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
#line = line.rstrip()
words = line.split()
for word in words:
if word not in lst:
lst.append(word)
lst.sort()
print(lst)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451322.html
下一篇:ValueError:具有多個元素的陣列的真值不明確。使用a.any()或a.all()-后跟TypeError
