4 回答
![?](http://img1.sycdn.imooc.com/54584d9f0001043b02200220-100-100.jpg)
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)
![?](http://img1.sycdn.imooc.com/545868190001d52602200220-100-100.jpg)
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))
![?](http://img1.sycdn.imooc.com/545863b500014e4602200220-100-100.jpg)
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。
![?](http://img1.sycdn.imooc.com/5333a0350001692e02200220-100-100.jpg)
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))
添加回答
举报