4 回答

TA貢獻1111條經驗 獲得超0個贊
words = set()
with open('path/to/romeo.txt') as file:
for line in file.readlines():
words.update(set(line.split()))
words = sorted(words)

TA貢獻1786條經驗 獲得超11個贊
以下應該有效:
fname = input("Enter file name: ")
with open(fname, 'r') as file:
data = file.read().replace('\n', '')
# Split by whitespace
arr = data.split(' ')
#Filter all empty elements and linebreaks
arr = [elem for elem in arr if elem != '' and elem != '\r\n']
# Only unique elements
my_list = list(set(arr))
# Print sorted array
print(sorted(arr))

TA貢獻1995條經驗 獲得超2個贊
要讀取文本文件,您必須先打開它:
with open('text.txt', 'r') as in_txt:
values = in_txt
l=[]
for a in values:
l.extend(a.split())
print(l)
用于with確保您的文件已關閉。'r'用于只讀模式。 extend將從列表中添加元素,在本例中a添加到現有列表中l。

TA貢獻1786條經驗 獲得超13個贊
在 python 中使用sets 比示例中的 list 更好。
集合是沒有重復成員的可迭代對象。
# open, read and split words
myfile_words = open('romeo.txt').read().split()
# create a set to save words
list_of_words = set()
# for loop for each word in word list and it to our word list
for word in myfile_words:
list_of_words.add(word)
# close file after use, otherwise it will stay in memory
myfile_words.close()
# create a sorted list of our words
list_of_words = sorted(list(list_of_words))
添加回答
舉報