[英]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.