我讀與詞的文件,像這樣列出:蟒蛇:增加STR和str.title()使用列表理解
stop_words = [x for x in open('stopwords.txt', 'r').read().split('\n')]
,但我還需要在這個詞的標題()版本相同的列表。我可以使用一個列表理解來做到這一點嗎?
我讀與詞的文件,像這樣列出:蟒蛇:增加STR和str.title()使用列表理解
stop_words = [x for x in open('stopwords.txt', 'r').read().split('\n')]
,但我還需要在這個詞的標題()版本相同的列表。我可以使用一個列表理解來做到這一點嗎?
在一個(嵌套)列表理解:
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())]
啊對,這就更好了!再次感謝! – user3813234
@ZachGates你甚至可以在f中使用''x,儘管我認爲這會保持換行符 –
您可以使用:
stop_words = [[x, str(x).title()] for x in open('stopwords.txt', 'r').read().split('\n')]
將產生嵌套列表。
[ [x, x titled], [y, y titled] ...]
他們希望'[x,x.title(),y,y.title(),...]' –
抱歉,我不明白,使用嵌套列表修復 – SyedElec
應在一行代碼是可行的:
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')]
你是什麼意思'標題()version' – MooingRawr
@MooingRawr他很可能意味着'x.title()' –
@MooingRawr是的,這就是我的意思。抱歉! – user3813234