删除带空格的单词

2024-04-20 09:22:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在中找到列表中的所有“短语”并从列表中删除它们,这样我就只剩下单词(没有空格)。我在做一个刽子手类型的游戏,希望电脑随机选择一个单词。我对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)

Tags: 代码in游戏类型列表forline单词
3条回答
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,因此它从括号内的语句构建一个列表。^{}是一个函数,它接受iterable,将提供的函数应用于iterable中的每个项,将每个转换的结果放入一个新的列表*。^{}是一个函数,它接受一个iterable,根据提供的谓词测试每一项,将计算为True的每一项放入一个新的列表*。^{}用于在线定义一个函数(具有特定的签名)。你知道吗

*:实际的返回类型是generators,它的功能类似于迭代器,因此它们仍然可以与for循环一起使用。你知道吗

使用str.split()。默认情况下,它以空格和换行符分隔。你知道吗

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

正常读取文件并按以下方式列出:

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

那应该很好。你知道吗

集合比列表更有效。当像这里这样懒洋洋地构建时,您可以获得显著的性能提升。你知道吗

# 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))

相关问题 更多 >