0

I am new to Python so I don't know how to find all 6 letter word in a text file then randomly select one of those words.
First problem: I don't know how to locate the path to the file in Mac. I know it should be something like this:

infile = open(r'C:\Users\James\word.txt', 'r')

Second problem: Do I create an empty list then transfer the word in text file to the list then use for loop?
Like:

words = ['adcd', 'castle', 'manmen']
for n in words:
   if len(n) ==6:
      return n

Third problem: Then how do I get a random word in list?

martineau
  • 119,623
  • 25
  • 170
  • 301
James
  • 5
  • 1
  • 2
  • 5

4 Answers4

1

You could use regex to find all the 6 letter words:

import re
word_list = list()
with open('words.txt') as f:
    for line in f.readlines():
        word_list += re.findall(r'\b(\w{6})\b', line)

regex in action:

In [129]: re.findall(r'\b(\w{6})\b', "Here are some words of varying length")
Out[129]: ['length']

Then use random.choice to pick a random word from that list:

import random
word = random.choice(word_list)
Cory Madden
  • 5,026
  • 24
  • 37
0

First, put your file in the same folder as the .py file.

Then try this:

# Create a list to store the 6 letter words
sixLetterWords= []
# Open the file
with open('word.txt') as fin:
    # Read each line
    for line in fin.readlines():
        # Split the line into words
        for word in line.split(" "):
            # Check each word's length
            if len(word) == 6:
                # Add the 6 letter word to the list
                sixLetterWords.append(word)
# Print out the result
print(sixLetterWords)
Milk
  • 2,469
  • 5
  • 31
  • 54
0

If you are on Python 3.5 or better, do yourself a favor and learn to use pathlib.Path objects. To find a file in your user home directory, simply do this:

from pathlib import Path

home_path = Path.home()
in_path = home_path/'word.txt'

Now in_path is a path-like object pointing to a file called "word.txt" in the top of your user home directory. You can safely and easily get the text out of that object, and split it into individual words as well, this way:

text = in_path.read_text() # read_text opens and closes the file
text_words = text.split() # splits the contents into list of words at all whitespace

Use the append() method to add words to your word list:

six_letter_words = []
for word in text_words:
    if len(word) == 6:
        six_letter_words.append(word)

The last 3 lines can be shortened using a list comprehension, which is very nice Python syntax for creating the list in place (without writing a for loop or using the append method):

six_letter_words = [word for word in words if len(word) == 6]

If you want to make sure you don't get words with numbers and punctuation, use an isalpha() check:

six_letter_words = [word for word in words if len(word) == 6 and word.isalpha()]

If numbers are OK but you don't want punctuation, use an isalnum() check:

six_letter_words = [word for word in words if len(word) == 6 and word.isalnum()]

Finally: for a random word in your list, use the choice function from the random module:

import random

random_word = random.choice(six_letter_words)
Rick
  • 43,029
  • 15
  • 76
  • 119
0

I think the following does what you want and effectively answers all of your sub-questions.

Note that split() divides the contents the file into list of words separated by whitespace (such as spaces, tabs, and newlines).

Also note that I used a word.txt file with just those three words from your question in it for illustration.

import random
import os

with open(os.path.expanduser('~James/word.txt'), 'r') as infile:
    words = [word for word in infile.read().split() if len(word) == 6]

print(words)  # -> ['castle', 'manmen']
print(random.choice(words))  # -> manmen
martineau
  • 119,623
  • 25
  • 170
  • 301