繁体   English   中英

在文本文件中找到6个字母单词

[英]Find 6 letter words in a text file

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

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

第二个问题:我是否创建一个空列表,然后将文本文件中的单词传输到列表中,然后使用for循环?
喜欢:

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

第三个问题:那我该如何在列表中得到一个随机单词?

您可以使用正则表达式查找所有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)

首先,将文件与.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)

如果您使用的是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模块中choice函数:

import random

random_word = random.choice(six_letter_words)

我认为以下内容可以满足您的要求,并且可以有效回答所有子问题。

请注意, 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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