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

标签 python python-2.7

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

['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

关于python - 将文本从文件转换为python中的字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37197822/

相关文章:

python - 使用 urllib2 登录网站 - Python 2.7

Python 在嵌套循环中求平均值

python - 如何在Python上制作具有不同大小的最后一个参数的3D矩阵

python 模块和导入

python - 如何将 Cassandra map 转换为 Pandas Dataframe

python - 同时循环三个列表 : nested loop not working

python - 修改 OPTPARSE 、 python 中的默认帮助消息 (-h)

python - PyQt5 Python 透明 QWebViewEngine

Python 和 PyQt : Catch Minimize Event

Python 脚本不会在 Linux 上创建文本文件