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

时间:2016-05-12 21:34:54

标签: 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()

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

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

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

4 个答案:

答案 0 :(得分:3)

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

lst += line.split()

.sort()对数组进行排序,并且不返回已排序的数组。你可以使用

print sorted(lst)

lst.sort()
print lst

答案 1 :(得分:3)

使用extend代替append

lst = list()

fname = raw_input("Enter file name: ")
with open(fname) as fh:
    for line in fh:
        lst.extend(line.rstrip.split()) # `rstrip` removes trailing whitespace characters, like `\n`

print(lst)
lst.sort() # Sort the items of the list in place
print(lst)

Python - append vs. extend

  • append:在最后添加对象。
  • extend:通过附加可迭代的元素来扩展列表。

答案 2 :(得分:1)

使用file.read()读取整个文件,并将该字符串拆分为空格为str.split()的地方:

with open(raw_input("Enter file name: "), 'r') as f:
    words = f.read().split()
print words
print sorted(words)

答案 3 :(得分:0)

最后,我明白了。这就是我想要的。

fname = raw_input("Enter file name: ")
fh = open(fname).read().split()
lst = list()
for word in fh:
    if word in lst:
        continue
    else:
        lst.append(word)
print sorted(lst)