2017-02-26 56 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模块可能对未来的语言处理任务有用。

希望这会有所帮助!