[英]convert a text from a file to a list of strings in 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
我完全迷路了。 我做錯了什么?
.split()
返回一個列表。 因此,您要將返回的列表附加到lst
。 相反,您想合並兩個列表:
lst += line.split()
.sort()
對數組進行原位排序,而不返回排序后的數組。 您可以使用
print sorted(lst)
要么
lst.sort()
print lst
使用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)
append
:在末尾追加對象。 extend
:通過添加來自iterable的元素來擴展列表。 閱讀與整個文件file.read()
和只要有空白與拆分字符串str.split()
with open(raw_input("Enter file name: "), 'r') as f:
words = f.read().split()
print words
print sorted(words)
終於我明白了。 這就是我想要的。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.