2017-02-26 63 views
0

我想在列表中找到所有「短語」,將它們從列表中刪除,這樣我只剩下單詞(沒有空格)。我正在做一個hang子手式的遊戲,並希望電腦選擇一個隨機單詞。我不熟悉Python和編碼,所以我很高興聽到我的代碼的其他建議。刪除帶空格的單詞

import random 
fhand = open('common_words.txt') 

words = [] 

for line in fhand: 
    line = line.strip() 
    words.append(line) 

for word in words: 
    if ' ' in word: 
     words.remove(word) 

print(words) 

回答

0

集合比列表更有效率。當像這樣懶散地構建時,你可以獲得顯着的性能提升。

# Load all words 
words = {} 
with open('common_words.txt') as file: 
    for line in file.readlines(): 
     line = line.strip() 
     if " " not in line: 
      words.add(line) 
# Can be converted to one-liner using magic of Python 
words = set(filter(lambda x: " " in x, map(str.strip, open('common_words.txt').readlines()))) 

# Get random word 
import random 
print(random.choice(words)) 
+0

'if「」not in line:' 這是我想要做的關鍵。我將不得不查看組和列表之間的差異。謝謝! –

0

使用str.split()。默認情況下,它由空格和換行符分隔。

>>> 'some words\nsome more'.split() 
['some', 'words', 'some', 'more'] 
>>> 'this is a sentence.'.split() 
['this', 'is', 'a', 'sentence.'] 
>>> 'dfsonf 43 SDFd [email protected]'.split() 
['dfsonf', '43', 'SDFd', '[email protected]'] 

正常讀取該文件,並列出清單是這樣的:

words = [] 
with open('filename.txt','r') as file: 
    words = file.read().split() 

這應該是不錯的。

0
with open('common_words.txt', 'r') as f: 
    words = [ word for word in filter(lambda x: len(x) > 0 and ' ' not in x, map(lambda x: x.strip(), f.readlines())) ] 

with被使用,因爲文件對象content managers。奇怪的類似列表的語法是list comprehension,所以它從括號內的語句構建了一個列表。 map是一個函數,它接受一個迭代器,將一個提供的函數應用於迭代器中的每個項目,將每個變換後的結果放入一個新列表*中。 filter是一個函數,它接受一個迭代,根據提供的謂詞測試每個項目,將每個項目評估爲True放入一個新列表*。 lambda用於定義一個函數(具有特定簽名)。

*:實際返回類型爲generators,其功能類似於迭代器,因此它們仍可以與for循環一起使用。

0

我不知道如果我理解正確,但我猜split()方法是東西給你,比如:

with open('common_words.txt') as f: 
    words = [line.split() for line in f] 

words = [word for words in words_nested for word in words] # flatten nested list 
0

如前所述, .split()方法 可能是解。

此外,NLTK模塊可能對未來的語言處理任務有用。

希望這會有所幫助!