简体   繁体   中英

Remove words with spaces

I want to find all the "phrases" in a list in remove them from the list, so that I have only words (without spaces) left. I'm making a hangman type game and want the computer to choose a random word. I'm new to Python and coding, so I'm happy to hear other suggestions for my code as well.

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)

Use str.split() . It separates by both spaces and newlines by default.

>>> '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']

Read the file normally and make a list this way:

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

That should be good.

Sets are more efficient than lists. When lazily constructed like here, you can gain significant performance boost.

# 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))
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 is used because file objects are content managers . The strange list-like syntax is a list comprehension , so it builds a list from the statements inside of the brackets. map is a function with takes in an iterable, applying a provided function to each item in the iterable, placing each transformed result into a new list*. filter is function which takes in an iterable, testing each item against the provided predicate, placing each item which evaluated to True into a new list*. lambda is used to define a function (with a specific signature) in-line.

*: The actual return types are generators , which function like iterators so they can still be used with for loops.

I am not sure if I understand you correctly, but I guess the split() method is something for you, like:

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

As mentioned, the .split() Method could be a solution.

Also, the NLTK module might be useful for future language processing tasks.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM