2016-05-12 53 views
1

我想读的文本文件,并从所有行提取每一个字,使字符串列表如下图所示:从文件转换为文本字符串列表在python

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

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

+0

文本文件的格式是什么? – pzp

+0

它是一种平面的文字file.But柔和什么光那边窗子里 那是东方朱丽叶就是太阳 起来美丽的太阳,杀死羡慕月亮 谁已经面色惨白悲伤 –

回答

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) 
+0

'set'更快。这就是你所需要的,'print(sorted(set(open(fname).read()。split())))' – SparkAndShine

3

.split()返回一个列表。因此您将返回的列表追加到lst。相反,你要Concat的2名列表:

lst += line.split() 

.sort()排序到位数组,并不会返回数组排序。您可以使用

print sorted(lst) 

lst.sort() 
print lst 
+0

的连接运算符的替代相当于['list.extend()'](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists)。 – pzp

+0

但是,然后lst.sort()只给了None。 –

+0

@Mehmood,'.sort()'对你的列表进行排序,并且不返回排序列表 – Fabricator

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:通过从迭代中追加元素来扩展列表。
1

阅读与file.read()整个文件,只要有空白与str.split()拆分字符串:

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

我仅限于使用split(),append()和sort()命令。 –

+0

@Mehmood你说你在可以使用的功能上有限,但是你发布了一个完全复制我的方法的答案。是什么赋予了? – pzp

+0

你没有使用append()方法,而是使用了很好的编程技巧,我希望有一天能够实现这种掌握。我需要用上面提到的命令以简单的方式编写代码,程序也应该排除列表中的重复字符串。 –

相关问题