2016-11-10 192 views
3

我讀與詞的文件,像這樣列出:蟒蛇:增加STR和str.title()使用列表理解

stop_words = [x for x in open('stopwords.txt', 'r').read().split('\n')] 

,但我還需要在這個詞的標題()版本相同的列表。我可以使用一個列表理解來做到這一點嗎?

+1

你是什麼意思'標題()version' – MooingRawr

+1

@MooingRawr他很可能意味着'x.title()' –

+0

@MooingRawr是的,這就是我的意思。抱歉! – user3813234

回答

5

在一個(嵌套)列表理解:

stop_words = [y for x in open('stopwords.txt', 'r').read().split('\n') for y in (x, x.title())] 

編輯:實際上,你不應該像這樣做,因爲您將文件對象丟失到打開的文件並且無法關閉它。您應該使用上下文管理器:

with open('stopwords.txt', 'r') as f: 
    stop_words = [y for x in f.read().split('\n') for y in (x, x.title())] 
+0

啊對,這就更好了!再次感謝! – user3813234

+0

@ZachGates你甚至可以在f中使用''x,儘管我認爲這會保持換行符 –

0

您可以使用:

stop_words = [[x, str(x).title()] for x in open('stopwords.txt', 'r').read().split('\n')] 

將產生嵌套列表。

[ [x, x titled], [y, y titled] ...] 
+1

他們希望'[x,x.title(),y,y.title(),...]' –

+0

抱歉,我不明白,使用嵌套列表修復 – SyedElec

0

應在一行代碼是可行的:

stop_words = [x for x in open('stopwords.txt', 'r').read().split('\n')] + [x.title() for x in open('stopwords.txt', 'r').read().split('\n')] 
+2

這將是2解析。 – jbndlr

+0

One liner!=一個列表理解。 –

+0

感謝您的回覆!但我正在尋找Patrick Haugh發佈的 – user3813234