3 回答

TA贡献1872条经验 获得超4个赞
line.split() 为您提供一个列表,该列表将作为列表对象添加到您的 lst 列表中。因此,而不是使用 lst.append(line) 使用 lst.extend(line) 来获得正确的输出。

TA贡献1906条经验 获得超10个赞
我了解您要实现的目标。这里有一个更简单的方法,而不是你写的方式:
import re
ls=set(re.findall(r"[\w']+", text)) #text is the input
print(sorted(ls))
测试它以确保它有效:
编辑:
我稍微修改了您的代码以满足您的用例。
fh = open(raw_input("Enter file name: "),'r')
lst = list()
for line in fh:
words = line[:-1].split(" ")
for word in words:
if word not in lst:
lst.append(word)
print(sorted(lst))
输出:
Enter file name: file.txt
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grie', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
希望能解决您的问题。

TA贡献1836条经验 获得超4个赞
output = []
with open('file_name') as f:
for i in f.readlines():
for j in words_to_split:
i = ''.join(i.split(j))
output.append(i)
添加回答
举报