如果您使用的是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
module的choice
功能:
import random
random_word = random.choice(six_letter_words)
恩,Mac没有C:\驱动器,所以第一个代码不正确 –
将文本文件放在与.py文件相同的目录中。然后使用'open('word.txt')'没有路径。 –
你的python文件位于你的文本文件的哪里? –