簡體   English   中英

從 Python 中的文件中讀取隨機行,這些行在其他 4 行通過之前不會重復

[英]Reading random lines from a file in Python that don't repeat untill 4 other lines have passed

所以我正在嘗試制作一個可以幫助人們學習新語言的程序,但我已經陷入困境。 其中一項要求是讓 Python 以隨機順序打印行。 所以我做了這個。

import random

def randomline(file):
    with open(file) as f:
        lines=f.readlines()
        print(random.choice(lines))

但是現在我遇到了其他要求之一的問題。 在單詞可以再次顯示之前必須有 4 個其他單詞,我不知道該怎么做。

我有一個非常原始的解決方案給你:

import random 

def randomline(file):
    with open(file) as f:
        lines=f.readlines()
        return random.choice(lines)

isOccuredInLastFourExistence = True
LastFourWords = []

file = "text_file.txt"
for i in range(0,15):
    new_word = randomline(file)
    print(LastFourWords)
    if new_word in LastFourWords:
        print("I have skipped")
        print(new_word)
        continue
    print(new_word)
    LastFourWords.append(new_word)
    if(len(LastFourWords)) > 4:
        LastFourWords.pop(0)

該文件如下所示:
在此處輸入圖像描述


輸出看起來像:(僅顯示部分結果)

[]
New

['New\n']
Example

['New\n', 'Example\n']
After

['New\n', 'Example\n', 'After\n']
Some

['New\n', 'Example\n', 'After\n', 'Some\n']
I have skipped
Example

['New\n', 'Example\n', 'After\n', 'Some\n']
Please

['Example\n', 'After\n', 'Some\n', 'Please\n']
I have skipped
Please

['Example\n', 'After\n', 'Some\n', 'Please\n']
Only

['After\n', 'Some\n', 'Please\n', 'Only\n']
Word
['Some\n', 'Please\n', 'Only\n', 'Word']
New

因此,每次您的列表中已經存在的內容都會被跳過。 並且列表在超過4個元素時清空第一個位置元素。

你可以使用隊列:

# create list with empty elements against which choice is checked
queue = 4*['']

def randomline(file):
    with open(file) as f:
        lines=f.readlines()
        choice = random.choice(lines)
        if not choice in queue:
            print(choice)

            # appendcurrent word to the queue
            queue.append(choice)
            # remove the first element of the list
            queue.pop(0)

您可以使用collections庫中的deque 這將允許您為看到的單詞列表指定最大長度。 當您將項目附加到列表時,如果您的列表達到最大長度並且您附加一個新項目,則最舊的項目將被刪除。 這允許你做一個緩存。 因此,如果您使用最大長度為 4 的deque創建一個列表。然后您選擇一個單詞並檢查它是否在列表中,如果是,則選擇另一個單詞,如果它不在列表中,則打印該單詞並將其添加到列表中. 您不必擔心管理列表中的項目,因為當您添加新內容時,最舊的項目會自動退出

from collections import deque
from random import choice, sample

with open('test.dat') as words_file:
    words = words_file.readlines()
    word_cache = deque(maxlen=4)
    for _ in range(30):
        word = choice(words).strip()
        while word in word_cache:
            word = choice(words).strip()
        print(word)
        word_cache.append(word)

我會使用linecache 它來自標准庫,允許您選擇特定行。 如果您知道文件中的行數,這可能會起作用:

import linecache
import random

def random_lines(filename, repeat_after=4):

    n_lines = len(open(filename, "r").readlines())
    last_indices = []

    while True:

        index = random.randint(1, n_lines)

        if index not in last_indices:

            last_indices.append(index)
            last_indices = last_indices[-repeat_after:]

            line = linecache.getline(filename, index)
            yield line

這將創建一個生成器,它將從您的文件中輸出隨機行,而無需將您的行保存在內存中(如果您開始有很多行,這很好)。

至於你的要求只允許重復n次。 這將解決它。 但是,這有很小的機會陷入無限循環。

另一種方法是創建一個包含所有索引(即行號)的列表,將其打亂,然后循環遍歷它們。 這樣做的好處是不會陷入無限循環,但這也意味着您需要遍歷所有其他行才能再次看到同一行,這對您來說可能並不理想。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM