簡體   English   中英

從 txt 文件一次打印 10 個單詞

[英]printing the 10 words at a time from a txt file

我正在嘗試打印 txt 文件中的前 10 個單詞,然后是接下來的 10 個單詞,然后是下一個......

這是我目前擁有的


text_file= open("read_it.txt", "r")
lines= text_file.readlines()
lineNum= 0
words= lines[lineNum].split()
wordNum= 0
text_file.close()


def printWords():
    global wordNum
    global lineNum
    global words
    lineNum= lineNum+1
    words= lines[lineNum].split()
    wordNum= 0
    print(words[wordNum])
    wordNum=wordNum+1
    print(words[wordNum])
    wordNum=wordNum+1

但如果我這樣做,我必須有 2 行 10 次我想知道是否有更有效的方法來做到這一點

我建議您使用正則表達式並將其拆分為單詞,而不是按行拆分並將行拆分為單詞。 我會這樣做

# Get list of words from file "word_filename", default to "test.txt"
def get_words(word_filename='test.txt'):
    # Regular expression library for re.split
    import re
    # Open the text file
    with open(word_filename, 'r') as file:
        # Generate the word list (Split with non-word as delimiter)
        yield from re.split(r'\W+', file.read())

# Get a list of "limit" words, default to 10
def get_n_words(limit=10):
    # Initialize the word list to store 10 words
    words = []
    # Loop through all the words
    for word in get_words():
        # Skip empty word
        if len(word) == 0: continue
        # Check if the word list have "limit" number of words
        if len(words) == limit:
            # Returns the word list
            yield words
            # Reset the word list
            words = []
        # The word list does not have enough size of "limit"
        else:
            # Insert the word
            words.append(word)
    # Check the remaining word list in case it doesn't have size of "limit"
    if len(words) > 0: yield words

# Loop through the 10 word lists
for ten_words in get_n_words():
    # Print the 10 words comma separated
    print(', '.join(ten_words))

暫無
暫無

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

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