2017-08-07 76 views
0

我是Python的新手,所以我不知道如何在文本文件中查找所有6个字母的单词,然后随机选择其中一个单词。
第一个问题:我不知道如何在Mac中找到文件的路径。 我知道它应该是这样的:在文本文件中查找6个字母的单词

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

问题二:我创建一个空的名单,然后在文本文件中的单词转移到列表,然后使用循环?
像:

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

第三个问题:那我怎么在列表中的随机字?

+1

恩,Mac没有C:\驱动器,所以第一个代码不正确 –

+1

将文本文件放在与.py文件相同的目录中。然后使用'open('word.txt')'没有路径。 –

+0

你的python文件位于你的文本文件的哪里? –

回答

0

首先,将您的文件放在与.py文件相同的文件夹中。

那就试试这个:

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

你可以使用正则表达式来发现所有的6个字母的单词:

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) 

正则表达式在行动:

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

然后使用random.choice挑来自该列表的随机词:

import random 
word = random.choice(word_list) 
0

如果您使用的是Python 3.5或更高版本,请自己帮忙,并学习使用pathlib.Path对象。要查找用户主目录中的文件,只要做到这一点:

from pathlib import Path 

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

现在in_path是指向在用户主目录的顶部被称为“WORD.TXT”文件的路径状物体。您可以安全,轻松地获取文本指出的对象,并把它分割成单个的词为好,这样说:

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 

使用append()方法将单词添加到您的单词列表:

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

最后3行可以使用列表理解,这是非常好的Python语法创建代替列表(而无需编写一个for循环或使用append方法)被缩短:

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

如果你想确保你不会用数字和标点符号得到的话,使用isalpha()检查:

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

如果数字是确定的,但你不想标点符号,使用isalnum()检查:

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

最后:在你的列表中随机字,使用来自random modulechoice功能:

import random 

random_word = random.choice(six_letter_words) 
0

我觉得FO在做你想做的事情,并有效地回答你所有的子问题。

请注意,split()将文件的内容分割成由空格(如空格,制表符和换行符)分隔的单词列表。

另外请注意,我使用了一个word.txt文件,其中只有您的问题中的三个单词用于说明。

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 
相关问题