Skip to main content
 首页 » 编程设计

python之将文本从文件转换为python中的字符串列表

2025年05月04日28TianFang

我想读取一个文本文件并从所有行中提取每个单词以制作如下字符串列表:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 
'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 
'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder'] 

我写了这段代码:

fname = raw_input("Enter file name: ") 
fh = open(fname) 
lst = list() 
for line in fh: 
    lst.append(line.split()) 
print lst 
print lst.sort() 

当我最后对它进行排序时,它只给出一个 None。 我得到了这个意想不到的结果!

[['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks'], 
['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'], ['Arise',  
'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon'], ['Who', 'is', 
'already', 'sick', 'and', 'pale', 'with', 'grief']] 
None 

我完全迷路了。我做错了什么?

请您参考如下方法:

.split() 返回一个列表。因此,您将返回的列表附加到 lst。相反,您想连接 2 个列表:

lst += line.split() 

.sort() 对数组进行就地排序,并且不返回排序后的数组。您可以使用

print sorted(lst) 

或

lst.sort() 
print lst