2016-05-12 51 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()方法,而是使用了很好的編程技巧,我希望有一天能夠實現這種掌握。我需要用上面提到的命令以簡單的方式編寫代碼,程序也應該排除列表中的重複字符串。 –

相關問題